MATLAB Answers

Finding maximum number location in a matrix

조회 수: 4(최근 30일)
Charms
Charms 3 Dec 2019
Commented: Charms 3 Dec 2019
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 3 Dec 2019
Stephen Cobeldick 님이 편집함. 3 Dec 2019
"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 3 Dec 2019
thanks stephen for explaining this so clearly, really appreciate it :)

로그인 to comment.

More Answers (0)

이 질문에 답변하려면 로그인을(를) 수행하십시오.


Translated by