필터 지우기
필터 지우기

Question about using randperm in a loop

조회 수: 3 (최근 30일)
Veena Chatti
Veena Chatti 2020년 3월 9일
댓글: Veena Chatti 2020년 3월 10일
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

채택된 답변

John D'Errico
John D'Errico 2020년 3월 10일
편집: John D'Errico 2020년 3월 10일
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
Veena Chatti
Veena Chatti 2020년 3월 10일
Hi John,
Thanks, reshape worked!
Best,
Veena
Veena Chatti
Veena Chatti 2020년 3월 10일
And yes, I got rid of the loop!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

James Tursa
James Tursa 2020년 3월 10일
편집: James Tursa 2020년 3월 10일
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
Veena Chatti
Veena Chatti 2020년 3월 10일
Hi James,
Thanks, reshape worked!
Best,
Veena

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by