MATLAB Answers

Finding maximum number location in a matrix

4 ビュー (過去 30 日間)
Charms
Charms 2019 年 12 月 3 日
Commented: Charms 2019 年 12 月 3 日
I have a 8x6 matrix (A) and would like to find the row location of the max number in each column, thereby ending up with a 1x6 vector (row). Currently my line of code looks like this. However, I was returned with a row [1,1,1,1,1,1] and col [1,2,3,4,5,6]. The answer should be row [8,6,6,6,7,6] --> the location of max number in each column, and col [1,2,3,4,5,6]. Is there a reason why this line is wrong?
Thank you!
[row,col,v] = find(max(A));

  0 件のコメント

サインイン to comment.

採用された回答

Stephen Cobeldick
Stephen Cobeldick 2019 年 12 月 3 日
編集済み: Stephen Cobeldick 2019 年 12 月 3 日
"Is there a reason why this line is wrong?"
Yes, because you nested max inside find. Take a look at the output of max: what is it? (hint: it will be a row vector of the maximum value from each column of your matrix). As its description states, find returns the indices of non-zero elements, so it will return the indices of whichever of those vector values is non-zero (which could be none). Note that find does NOT know anything about your matrix A (or its size or indices etc), because its input is a row vector (the output of max).
One easy alternative is to get rid of the find entirely:
>> A = zeros(8,6);
>> A(8,1) = 1;
>> A(6,2) = 1;
>> A(6,3) = 1;
>> A(6,4) = 1;
>> A(7,5) = 1;
>> A(6,6) = 1
A =
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 1 1 1 0 1
0 0 0 0 1 0
1 0 0 0 0 0
>> [~,idr] = max(A,[],1)
idr =
8 6 6 6 7 6
>> idc = 1:size(A,2)
idc =
1 2 3 4 5 6
If you really must use find then probably the simplest solution is to generate a logical matrix as the input to find (note if the maximum values occurs more than once in one column this will return all of their indices, use cumsum to return only the first one):
>> [idr,idc] = find(bsxfun(@eq,A,max(A,[],1)))
idr =
8
6
6
6
7
6
idc =
1
2
3
4
5
6

  1 件のコメント

Charms
Charms 2019 年 12 月 3 日
thanks stephen for explaining this so clearly, really appreciate it :)

サインイン to comment.

More Answers (0)

サインイン してこの質問に回答します。


Translated by