How to find the index of a randomly chosen element of an array

43 ビュー (過去 30 日間)
feit feit
feit feit 2020 年 12 月 2 日
コメント済み: Ameer Hamza 2020 年 12 月 3 日
Would anyone suggest me the code of finding out the index of a randomly selected element of an array or matrix?
For example, after randomly selecting an element from 'a', I want to find out the index number of the chosen element. This index number should be a variable as each time i randomly select an element, the corresponding index number of the selected element may change.
a = [4 5 10 15 20];

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 12 月 2 日
Try this
idx = find(a==random_element)
  6 件のコメント
feit feit
feit feit 2020 年 12 月 3 日
Row number is the criteria. I will have a row number (which is also a variable) and i only need the combination corresponding to that particular row number.
Ameer Hamza
Ameer Hamza 2020 年 12 月 3 日
You can just apply find() to that row
a = [ 1 3 4; 1 4 5; 2 1 6];
row_num = 3;
random_element = 1;
col_num = find(a(row_num,:)==random_element)

サインインしてコメントする。

その他の回答 (1 件)

Steven Lord
Steven Lord 2020 年 12 月 2 日
Start off generating the index and use it to extract the element.
a = [4 8 15 16 23 42];
I = randi(numel(a));
fprintf("Element %d of a is %d\n", I, a(I))
Element 5 of a is 23
  1 件のコメント
feit feit
feit feit 2020 年 12 月 2 日
編集済み: feit feit 2020 年 12 月 2 日
Very helpful answer. Thank you!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by