Randomly selecting a number from different arrays

조회 수: 4 (최근 30일)
Sojung Youn
Sojung Youn 2021년 10월 13일
편집: Matt J 2021년 10월 19일
Hello,
I am trying to randomly select numbers from 3 different arrays without having them side by side or repeated. For example, I have 3 arrays like below and pick 1 random number from them with the code below.
A = [11 11 11 12 12 12 13 13]
B = [21 21 21 22 22 22 23 23]
C = [31 31 31 32 32 32 33 33]
I would need 18 string of numbers and would there a way to pick 1 random number from A, and for the next number it would come from only B or C? (and after that, the number would only come from the other two list.)
Many thanks!

답변 (1개)

Matt J
Matt J 2021년 10월 14일
A = [11 11 11 12 12 12 13 13];
B = [21 21 21 22 22 22 23 23];
C = [31 31 31 32 32 32 33 33];
M=[A;B;C];
I=mod(cumsum(randi(2,1,18)),3)+1;
J=randi(length(A),size(I));
selection=M( sub2ind(size(M),I,J) )
selection = 1×18
22 33 12 21 11 23 12 21 12 33 11 31 12 22 31 11 33 22
  댓글 수: 8
Sojung Youn
Sojung Youn 2021년 10월 19일
It is much closer to what I was expecting, but it seems like I keep getting different amount of numbers from the arrays. I will look into it a little more! Appreciate the help SO much!
Matt J
Matt J 2021년 10월 19일
편집: Matt J 2021년 10월 19일
You can't be guaranteed to get the same amount of numbers, because the rule you have specified in your post does not call for a pure permutation of the values in A,B,C. If you wanted a pure permutation you would simply do,
M=[A;B;C]
selection=M(randperm(numel(M)))
The rule you have specified, however, is that none of A,B,C can be selected twice in succession. This means, for example, that the sequence A,B,A,B,A,B,... with no occurence at all of C is hypothetically possible.

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

카테고리

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