Randomly select an element from a vector satisfying a condition
3 ビュー (過去 30 日間)
古いコメントを表示
Amirhossein Moosavi
2019 年 7 月 1 日
コメント済み: Arjun Siva S
2020 年 12 月 7 日
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
0 件のコメント
採用された回答
Amirhossein Moosavi
2019 年 7 月 1 日
2 件のコメント
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
2020 年 12 月 7 日
Thanks a lot! I've been thinking about the same problem for a long time.
その他の回答 (2 件)
Jos (10584)
2019 年 7 月 1 日
This is a two-step process:
- create an intermediate array with all elements of X satisfying your condition
- select a single element from that
You can combine the two steps in a single command:
randsample(X(X>2), 1)
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 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!