Elegant way to create two different random integers

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 

not really the smoothest thing you can do.

+5
source share
3 answers

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

 ri = randperm(n, 2); 

Older versions of MATLAB do not support calling randperm in this way. Older versions allow only one input option, which by default returns the entire permutation of n values. Therefore, you can call randperm with a single input version, then a subset of the final result to return what you need:

 ri = randperm(n); ri = ri([1 2]); 
+8
source

Use randperm to create two unique values ​​in the range 1 ... n

 out = randperm(n, 2) out(1) = number 1 out(2) = number 2 

If you want to include 0 in your range. then:

 out = randperm(n+1, 2); out = out-1; out(1) = number 1 out(2) = number 2 
+2
source

Here's another way:

 ri(1) = randi([1 n]); % choose ri(1) uniformly from the set 1,...,n ri(2) = randi([1 n-1]); % choose ri(2) uniformly from 1,...,n-1 ri(2) = ri(2) + (ri(2)>=ri(1)); % transform 1,...,n-1 into 1,...,ri(1)-1,ri(1)+1,...,n 
+2
source

Source: https://habr.com/ru/post/1264310/


All Articles