How can I use the multidimensional index returned by max or min?
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi all,
[M,I] = max(A, [], dim)
returns maximum values and the index of those maximum values along the specified dimension dim. When A is an multidimensional array, variable I turns out to be a multidimensional array with same dimension as A, except the dim dimension set to 1. My question is how do I use the index multidimensional array I to get back the max from the A.
To provide a specific use case, I want to obtain the complex number with maximum real part along the dimension dim, when A could contain complex numbers.
I can use
[M,I] = max(real(A), [], dim)
to get the maximum real parts and their indices. But, how do I get the original complex variable at those indices? I am particularly interested in cases where A has more than 2 dimensions.
Thanks in advance! N
0 commentaires
Réponses (1)
Roger Stafford
le 22 Mar 2016
There is a fairly obvious method using nested for-loops, so I assume you are looking for a vectorized method. I am not at all sure that the following would be faster, but you can try it out and see. Suppose, for example, that A is 5-dimensional and that your maximums are taken along the 3rd dimension. Then do this:
[M,I3] = max(real(A),[],3);
[n1,n2,n3,n4,n5] = size(A);
[I1,I2,I4,I5] = ndgrid(1:n1,1:n2,1:n4,1:n5);
I = sub2ind(size(A),I1(:),I2(:),I3(:),I4(:),I5(:));
C = reshape(A(I),n1,n2,1,n4,n5);
The necessary conversion to other numbers of dimensions and other values of 'dim' should be evident.
1 commentaire
Roger Stafford
le 25 Mar 2016
It has occurred to me that there is a somewhat less wasteful variation on the example I gave you, Nachiketa. Again suppose A is 5D and the maximums are taken along the 3rd dimension. Do this:
[~,J] = max(real(A),[],3);
[n1,n2,n3,n4,n5] = size(A);
[I,K] = ndgrid(1:n1*n2,1:n4*n5);
L = sub2ind([n1*n2,n3,n4*n5],I(:),J(:),K(:));
C = reshape(A(L),n1,n2,1,n4,n5);
Again it should be evident how this can be generalized to any number of dimensions and any value of 'dim'. There should never be any need to generate more than a two-dimensional grid from 'ndgrid' here, nor more than three vectors to be used in 'sub2ind' for this procedure. If the maximums were taken along the 2nd dimension, for example, the code would be changed to:
[~,J] = max(real(A),[],2);
[n1,n2,n3,n4,n5] = size(A);
[I,K] = ndgrid(1:n1,1:n3*n4*n5);
L = sub2ind([n1,n2,n3*n4*n5],I(:),J(:),K(:));
C = reshape(A(L),n1,1,n3,n4,n5);
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!