필터 지우기
필터 지우기

min/max indexing of array

조회 수: 2 (최근 30일)
Oscar Frick
Oscar Frick 2018년 6월 19일
댓글: Oscar Frick 2018년 6월 19일
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
  댓글 수: 1
Oscar Frick
Oscar Frick 2018년 6월 19일
Logical indexing is way better, thanks!

댓글을 달려면 로그인하십시오.

추가 답변 (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