Effacer les filtres
Effacer les filtres

min/max indexing of array

7 vues (au cours des 30 derniers jours)
Oscar Frick
Oscar Frick le 19 Juin 2018
Commenté : Oscar Frick le 19 Juin 2018
I have an array of values of the size (n,1,4), that contains Euclidian distances of vectors as well as some NaN values where the Euclidian distance is not applicable. An example of such a vector could be
E(:,:,1) =
NaN
722.6494
948.3222
E(:,:,2) =
286.7571
NaN
386.2155
E(:,:,3) =
NaN
NaN
115.6732
E(:,:,4) =
715.2429
227.8121
NaN
I want to set all but the minimum values along the 3:d dimension to NaN, but can't figure out how to use the indexing from min. I understand that
[~,I] = min(E,[],3)
Gives me the index value for each row, so in the above case I = [1, 4, 3].' - but how do I use this index in a meaningful sense to index the values I want to keep?

Réponse acceptée

Stephen23
Stephen23 le 19 Juin 2018
Modifié(e) : Stephen23 le 19 Juin 2018
Using a logical comparison is much simpler:
>> E(bsxfun(@ne,E,min(E,[],3))) = NaN
E =
ans(:,:,1) =
NaN
NaN
NaN
ans(:,:,2) =
286.76
NaN
NaN
ans(:,:,3) =
NaN
NaN
115.67
ans(:,:,4) =
NaN
227.81
NaN
Or the same for MATLAB versions with implicit array expansion (R2016b+):
E(E~=min(E,[],3)) = NaN
If you really need to use indexing then you will need to generate the subscript indices and then convert them into linear indices, e.g. using ndgrid and sub2ind:
[~,I] = min(E,[],3);
S = size(E);
S(end+1:4) = 1;
[R,C,~,F] = ndgrid(1:S(1),1:S(2),1,1:S(4));
X = sub2ind(S,R,C,I,F);
F = E;
F(:) = NaN;
F(X) = E(X)
giving exactly the same output:
F =
ans(:,:,1) =
NaN
NaN
NaN
ans(:,:,2) =
286.76
NaN
NaN
ans(:,:,3) =
NaN
NaN
115.67
ans(:,:,4) =
NaN
227.81
NaN
  1 commentaire
Oscar Frick
Oscar Frick le 19 Juin 2018
Logical indexing is way better, thanks!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrices and Arrays 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