How to choose a random value from an array?

조회 수: 378 (최근 30일)
Priya
Priya 2014년 6월 8일
댓글: Image Analyst 2021년 1월 29일
Hi,
I have an array of values and I need to frame an expression such that it chooses the value from the array automatically instead of me assigning a value from the array everytime. For example, if
A_index=[1 2 3 4]
B_index=[5 6 7 8]
while initialising A, B for the first time I choose A=2, and B=6 (A and B are selected with corresponding element) and next time A=4, B=8
However, I have used this coding
A=@(A_index) A_index(ceil(rand*length(A_index)))
B=@(B_index) B_index(ceil(rand*length(B_index)))
But this line doesn't generate a value, instead it returns the expression itself. Why is that so?
Could someone please help me.
  댓글 수: 2
dpb
dpb 2014년 6월 9일
A=@(A_index) A_index(ceil(rand*length(A_index)))
...this line doesn't generate a value, instead it returns the expression itself. Why is that so?
Because you defined A and B to be function handles.
Perhaps you're looking for something like
A=A_index(randperm(length(A_index),1));
maybe???
Priya
Priya 2014년 6월 9일
편집: Priya 2014년 6월 9일
No, its inconsistent. I mean sometimes it works but for other iteration when A=4, I get B as 7 instead of 8.

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

채택된 답변

dpb
dpb 2014년 6월 9일
Then you must want to only generate a single index instead of two and use it for both--
idx=randperm(length(A_index),1);
A=A_index(idx);
B=B_index(idx);

추가 답변 (1개)

Image Analyst
Image Analyst 2014년 6월 9일
How about
randomIndex = randi(length(A), 1)
selected_A_value = A(randomIndex)
Repeat for B after changing the A's to B's.
  댓글 수: 3
dpb
dpb 2021년 1월 28일
편집: dpb 2021년 1월 28일
Change the number of elements generated in the randi function in IA's way or the number of the permuations returned in my solution above. Depends upon whether the two are correlated as the original poster wanted as to which is the one you want.
And, of course, whether you use a random permutation of the indices 1:N or generate a realization of M integers over ranged of 1:N is also immaterial, both use the underlying pseudorandom number generator. Altho it has been around now for quite a long time, randi is a more recent introduction to MATLAB than randperm and I'm an old geezer so I tend to forget about it.
Image Analyst
Image Analyst 2021년 1월 29일
M = 20; % Whatever you want.
randomIndexes = randperm(length(A), M) % Get M random indexes.
selected_A_values = A(randomIndexes)
randomIndexes = randperm(length(B), M) % Get M random indexes.
selected_B_values = B(randomIndexes)

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

카테고리

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