Getting different values when indexing with islocalmax and find
Afficher commentaires plus anciens
I have a matrix of data A. and I want to find the maximum values in this matrix for each row. This is my script:
index_max_A = islocalmax(A,2);
max_A = A(index_max_A);
However, I find that this does not get me the maximum values. For reference I did:
for idx = 1: height(A)
max_A_2(idx) = A(idx, find(index_max_A(idx,:) == 1));
end
max_A_2 == max_A'
I dont get all logical 1. Can someone explain why that is?
I checked both max_A_2 and max_A, max_A_2 has the correct maximums.
Réponse acceptée
Plus de réponses (1)
The reason the elements of max_A_2 and max_A are not all equal has to do with how the results of indexing with a logical matrix are returned. Specifically, the elements are returned in column-major order (just like they are stored in memory). That is, you get all the elements corresponding to a true in the first column of the logical matrix, followed by all the elements corresponding to a true in the second column, and so on.
To illustrate with your data:
A = load('A.mat')
A = A.Pout_r
plot(A.')
index_max_A = islocalmax(A,2)
Notice that index_max_A is all false in the first 14 columns:
any(index_max_A(:,1:14),'all')
and that the 15th column has 6 elements that are true:
nnz(index_max_A(:,15))
which are in rows 1-3 and 31-33:
find(index_max_A(:,15))
Those 6 true elements in the 15th column correspond to the first 6 elements you get when you do this:
max_A = A(index_max_A)
See:
temp = A(find(index_max_A(:,15)),15) % 1st 6 elements of max_A come from the 15th column
isequal(temp,max_A(1:6))
The point is that max_A contains the elements of A that are local maxima, in column order, but you define max_A_2 to be in row order. That's why they're different (but the first three elements are the same because they happen to occur in the first three rows).
To have max_A be in row order, so to be consistent with max_A_2, index the transpose of A with the transpose of the logical matrix:
A_temp = A.';
max_A = A_temp(index_max_A.')
Now max_A is the same as max_A_2:
for idx = 1: height(A)
max_A_2(idx) = A(idx, find(index_max_A(idx,:) == 1));
end
max_A_2 == max_A'
isequal(max_A_2,max_A')
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
