フィルターのクリア

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 Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by