MATLAB Answers

Question about using randperm in a loop

3 views (last 30 days)
Hi,
I'm using randperm in a loop that's meant to generate unique random three-digit numbers to fill a 5x5 matrix, r, like this:
for i = 1:length(r)
r(1:5,i) = (randperm(900,5) + 99);
end
My question is:
Is there a possibility of repeating a number given the function is being called 5 times, once for each column? I want each number to be unique.
Thanks,
Veena

  0 Comments

Sign in to comment.

Accepted Answer

John D'Errico
John D'Errico on 10 Mar 2020
Edited: John D'Errico on 10 Mar 2020
So, you want to sample 5 sets of 5 numbers, all from the same set, but you want them to be unique? (The technical description would be to sample without replacement.)
The point is, you already know how to sample 5 such numbers. So just sample 25 numbers!
r = reshape(randperm(900,25) + 99,[5 5]);
There is no reason to need a loop.

  2 Comments

Veena Chatti
Veena Chatti on 10 Mar 2020
Hi John,
Thanks, reshape worked!
Best,
Veena
Veena Chatti
Veena Chatti on 10 Mar 2020
And yes, I got rid of the loop!

Sign in to comment.

More Answers (1)

James Tursa
James Tursa on 10 Mar 2020
Edited: James Tursa on 10 Mar 2020
If you want each number in the matrix to be unique, then don't call randperm( ) by row because that will not guarantee uniqueness between calls. Call randperm( ) only once for the entire matrix (25 elements) and then reshape to a 5x5. E.g., something like
r = reshape(randperm(900,25) + 99,5,5);

  1 Comment

Veena Chatti
Veena Chatti on 10 Mar 2020
Hi James,
Thanks, reshape worked!
Best,
Veena

Sign in to comment.

Sign in to answer this question.