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.
In a column, use =RAND() formula to generate a set of random numbers between 0 and 1.
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.
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With