Finding maximum number location in a matrix

1 vue (au cours des 30 derniers jours)
Cside
Cside le 3 Déc 2019
Commenté : Cside le 3 Déc 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));

Réponse acceptée

Stephen23
Stephen23 le 3 Déc 2019
Modifié(e) : Stephen23 le 3 Déc 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 commentaire
Cside
Cside le 3 Déc 2019
thanks stephen for explaining this so clearly, really appreciate it :)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by