How to find the index of a randomly chosen element of an array
조회 수: 10 (최근 30일)
이전 댓글 표시
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];
댓글 수: 0
채택된 답변
Ameer Hamza
2020년 12월 2일
Try this
idx = find(a==random_element)
댓글 수: 6
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
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))
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!