필터 지우기
필터 지우기

Generate random integers with a condition

조회 수: 2 (최근 30일)
Yesbol
Yesbol 2018년 3월 7일
댓글: Yesbol 2018년 3월 7일
Hi all,
I have a matrix A 84x1 (attached). I need to replace ZEROS by randi(3). However, I need to ensure that the number of 1s, 2s or 3s does not exceed 33.
Hope the problem is clear.
Thank you
  댓글 수: 3
Yesbol
Yesbol 2018년 3월 7일
Thanks for your response. Number of 1s, 2s and 3s for each values, i.e. I cannot have more than 33 1s or 33 2s or 33 3s. All zeros are to be replaced by an individual random value
Thanks
Jan
Jan 2018년 3월 7일
I've adjusted the code. See [EDITED]

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

채택된 답변

Jan
Jan 2018년 3월 7일
편집: Jan 2018년 3월 7일
% [EDITED] after the comment:
A = randi([0,5], 84, 1);
z = (A == 0);
nz = sum(z);
ready = false;
while ~ready
A(z) = randi(3, nz, 1);
ready = sum(A==1) < 33 && sum(A==2) < 33 && sum(A==3) < 33;
end
To be sure, add a maximum number of loops. Better stop with an error than run an infinite loop:
count = 0;
while ~ready && count < 1e6
...
count = count + 1;
end
if count == 1e6
error('Cannot find matching values.')
end
A constructive method might be better also: Create a pool with 32 1s, 2s and 3s, and select the elements randomly out of this pool:
pool = repelem(1:3, 32);
index = randperm(numel(pool), nz);
value = pool(index);
Now the vector value must contain less than 33 ones, twos or threes.
  댓글 수: 2
Yesbol
Yesbol 2018년 3월 7일
Thanks for your insights. Creating a pool and selecting the elements randomly out of this pool is a good point
Yesbol
Yesbol 2018년 3월 7일
Works perfectly! Cheers!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Random Number Generation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by