Max
Max

Reputation: 1481

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

is not really the smoothest thing you can do.

Upvotes: 5

Views: 541

Answers (3)

Luis Mendo
Luis Mendo

Reputation: 112659

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

Upvotes: 2

rayryeng
rayryeng

Reputation: 104464

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]);

Upvotes: 8

Tony Tannous
Tony Tannous

Reputation: 14856

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

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

If you wish to include 0's in your range. then:

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

Upvotes: 2

Related Questions