Randomly select an element from a vector satisfying a condition

조회 수: 11 (최근 30일)
Dear experts,
I would like to randomly select an element from a vector satisfying a condition. In fact, I want to know what is the fastest way. For example, suppose vector X defined as follows:
X = [1 2 3 4 5 2 3 6 7 8 8 7 9 10 0 1 2 3 8 5 6 4];
How should I randomly select and identify the index of an element in this vector, which is greater than 2?
Thanks for your help,
Amir

채택된 답변

Amirhossein Moosavi
Amirhossein Moosavi 2019년 7월 1일
I already have an answer to this question as follow (but I am seeking for faster solutions):
Ind = find(X > 2); Ind = Ind(randsample(1:numel(Ind), 1));
  댓글 수: 2
Bruno Luong
Bruno Luong 2019년 7월 2일
The solution seems fine and pretty optimal to me. If you insist on faster move away from MATLAB or buy a faster computer.
Arjun Siva S
Arjun Siva S 2020년 12월 7일
Thanks a lot! I've been thinking about the same problem for a long time.

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

추가 답변 (2개)

Jos (10584)
Jos (10584) 2019년 7월 1일
This is a two-step process:
  1. create an intermediate array with all elements of X satisfying your condition
  2. select a single element from that
You can combine the two steps in a single command:
randsample(X(X>2), 1)
  댓글 수: 1
Amirhossein Moosavi
Amirhossein Moosavi 2019년 7월 1일
Thanks for your time. This only gives the value of an element; while I want its index.

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


David Goodmanson
David Goodmanson 2019년 7월 2일
Relative speeds are going to depend on the length of X and the value N that the elements have to be greater than, (2 in the example). The following is generally faster, by a factor of 2 or so.
f = find(X > M); % M = 2
Ind = f(randi(length(f)));
  댓글 수: 3
David Goodmanson
David Goodmanson 2019년 7월 2일
I agree, although the question did specify a single draw.
Amirhossein Moosavi
Amirhossein Moosavi 2019년 7월 2일
You are right. Many thanks for your attention.

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by