필터 지우기
필터 지우기

Finding maximum number location in a matrix

조회 수: 1 (최근 30일)
Cside
Cside 2019년 12월 3일
댓글: Cside 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));

채택된 답변

Stephen23
Stephen23 2019년 12월 3일
편집: Stephen23 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
Cside
Cside 2019년 12월 3일
thanks stephen for explaining this so clearly, really appreciate it :)

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by