min/max indexing of array

2 次查看(过去 30 天)
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?

采纳的回答

Stephen23
Stephen23 2018-6-19
编辑:Stephen23 2018-6-19
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by