Last non nan observation

33 ビュー (過去 30 日間)
joseph Frank
joseph Frank 2012 年 2 月 18 日
コメント済み: Sven 2023 年 2 月 18 日
Hi,
I have a matrix and I want to find in each column the last non nan observation. Is there a neat way of doing it quickly? Regards

採用された回答

Jiro Doke
Jiro Doke 2012 年 2 月 18 日
I'm not sure if you're looking for the indices (row number) or the actual value of the last non nan observation. So here are both:
B = ~isnan(A);
% indices
Indices = arrayfun(@(x) find(B(:, x), 1, 'last'), 1:size(A, 2));
% values
Values = arrayfun(@(x,y) A(x,y), Indices, 1:size(A, 2));
  3 件のコメント
Poulomi
Poulomi 2023 年 2 月 18 日
how to overcome this snag @Sven ?
Sven
Sven 2023 年 2 月 18 日
See my answer below for a file exchange entry

サインインしてコメントする。

その他の回答 (1 件)

Sven
Sven 2012 年 2 月 18 日
Here I can plug a file exchange entry:
Im = rand(50);
Im(Im>.7) = nan;
lastNans = find_ndim(~isnan(Im),1,'last')
To quote: I = FIND_NDIM(BW,DIM,'last') returns the subscripts of the last nonzero elements of BW along the dimension DIM.
The solution hijacks the max() function... it's only a few lines but it packages up things nicely (such as returning 0 if no NaNs were found in a column) - hope you like it.
And if you don't want to use the function itself you can get your answer with just the relevant lines as follows:
BW = ~isnan(Im);
[~, foundPx] = max(BW,[],1);
foundPx = size(BW,1)+1 - foundPx; % Need to count backwards to get last non-zero
foundPx(~any(BW,dim)) = 0; % Account for all-zero entries by setting output to 0

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by