How to find the index of any maximum matrix?

조회 수: 3 (최근 30일)
vimal kumar chawda
vimal kumar chawda 2021년 7월 9일
댓글: DGM 2021년 7월 11일
I have matrix X=radn(20)
I need the index or position in column and row of the maximum value.
X =rand(20)
How can I ?
  댓글 수: 2
Image Analyst
Image Analyst 2021년 7월 11일
Wow, 107 tags, if I conted correctly. I think that must be a reconrd. It must have taken you more time to enter all those than to just look up max() in the help. I'll show you how to do it in my answer below.
Stephen23
Stephen23 2021년 7월 11일
@vimal kumar chawda: please do not add 107 completely unrelated tags to your questions.
You might not use tags, but you are not the only user of this forum, and some of us certainly do use tags.

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

채택된 답변

DGM
DGM 2021년 7월 9일
편집: DGM 2021년 7월 9일
s = [10 10];
x = randi(100,s)
x = 10×10
40 81 9 67 90 11 44 79 79 56 2 53 68 82 7 42 35 39 51 95 60 22 51 18 47 6 44 83 38 49 57 44 87 24 6 41 59 83 53 94 74 54 17 10 43 2 72 27 16 46 18 60 91 20 13 24 77 38 9 21 22 8 47 100 70 7 42 88 27 17 79 69 38 11 59 80 79 89 68 10 92 92 77 89 49 64 98 97 74 61 50 69 93 52 28 43 4 61 15 96
[~,idx] = max(x(:)) % this gets the linear index
idx = 37
[row col] = ind2sub(s,idx) % if you want subscripts instead
row = 7
col = 4
Of course, that's only the first instance of the maximal value.
  댓글 수: 4
Image Analyst
Image Analyst 2021년 7월 11일
Actually since his question used randn() which will give unique floating point values and only one max value, not several, your suggestion to use max() is fine.
DGM
DGM 2021년 7월 11일
I just used randi so that the matrix was easier to read by eye and fit better on the page. The fact that it allows for frequent duplicates was what prompted me to mention the behavior.

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

추가 답변 (1개)

Image Analyst
Image Analyst 2021년 7월 11일
m = randi(9, 5, 5)
maxValue = max(m(:))
% Find out what rows and columns the max occurs in.
% Works even if the max occurs in more than one place
% unlike the index the second output argument of max() gives you.
[rowsOfMax, columnsOfMax] = find(m == maxValue)
You'll see:
m =
3 5 7 9 8
7 9 3 5 3
6 4 5 2 8
2 6 7 2 3
2 3 9 3 9
maxValue =
9
rowsOfMax =
2
5
1
5
columnsOfMax =
2
3
4
5
Like I said, it's a more robust solution than using max() alone.

카테고리

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

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by