Finding maximum number location in a matrix
1 回表示 (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
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
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!