How to find the index of any maximum matrix?
1 回表示 (過去 30 日間)
古いコメントを表示
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
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
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
2021 年 7 月 9 日
編集済み: DGM
2021 年 7 月 9 日
s = [10 10];
x = randi(100,s)
[~,idx] = max(x(:)) % this gets the linear index
[row col] = ind2sub(s,idx) % if you want subscripts instead
Of course, that's only the first instance of the maximal value.
4 件のコメント
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
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
2021 年 7 月 11 日
@vimal kumar chawda, try this:
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.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!