Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to create two different random integers

Tags:

random

matlab

I want to create two random integers on the interval [1,n] which are guaranteed to be different from each other. I feel like

ri(1)=randi([1 n]);
ri(2)=randi([1 n]);
while ri(1)==ri(2)
  ri(2)=randi([1 n]);
end

is not really the smoothest thing you can do.

like image 222
Max Avatar asked Feb 16 '17 17:02

Max


People also ask

How do you generate a unique random number?

In a column, use =RAND() formula to generate a set of random numbers between 0 and 1.

How do you generate unique random numbers in Matlab?

You can use randperm . From the description: p = randperm(n,k) returns a row vector containing k unique integers selected randomly from 1 to n inclusive.


1 Answers

One method is to use randperm so that you generate a random permutation of n values that are enumerated from 1 up to and including n, and only return the first two elements of the result:

ri = randperm(n, 2);

Older versions of MATLAB do not support calling randperm this way. Older versions only accept the one input variant, which by default returns the entire permutation of the n values. Therefore, you can call randperm using the one input version, then subset into the final result to return what you need:

ri = randperm(n);
ri = ri([1 2]);
like image 94
rayryeng Avatar answered Sep 22 '22 04:09

rayryeng