How to find last and first column of matrix which is not NaN?

5 ビュー (過去 30 日間)
Kaia
Kaia 2012 年 9 月 18 日
Hi there,
Lets say I have 24 columns with 8760 rows. In some of the first columns (in some cases 1-5 columns are all NaNs) and last columns (for example 21-24) are 8760 NaNs. Is there some quick way to find the number (index) of the first column(s) where are at least some values which are not NaNs (1 not a NaN is also suitable), and the last column where all the rows are not NaN.
Many thanks,
Kaia

回答 (3 件)

José-Luis
José-Luis 2012 年 9 月 18 日
編集済み: José-Luis 2012 年 9 月 18 日
Index to first column:
idx_first = find(sum(~isnan(your_data),1) > 0, 1 ,'first')
Index to the last column:
idx_last = find(sum(~isnan(your_data),1) > 0, 1 , 'last')
  2 件のコメント
Kaia
Kaia 2012 年 9 月 18 日
I tried it, but i`m getting this error:
Error using find Second argument must be a positive scalar integer.
José-Luis
José-Luis 2012 年 9 月 18 日
My bad, I forgot a 1 in there. See my edited answer.

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


Andrei Bobrov
Andrei Bobrov 2012 年 9 月 18 日
編集済み: Andrei Bobrov 2012 年 9 月 21 日
A - your array with NaN;
t = ~isnan(A);
idx0 = [find(any(~t) & any(t)),find(all(t))];
idx = idx0([1,end]);
  2 件のコメント
Andrei Bobrov
Andrei Bobrov 2012 年 9 月 18 日
corrected
Andrei Bobrov
Andrei Bobrov 2012 年 9 月 21 日
corrected 2

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


Image Analyst
Image Analyst 2012 年 9 月 18 日
I think this handles all cases that you might care about:
%-------------------------------------------------
% Generate some sample data.
m = randi(9, [8760,24]);
% Make first 5 columns all NaNs
m(:, 1:5) = nan;
% Make column 7 have mostly NaNs but a few non-Nan values.
m(10:end, 7) = NaN;
% Make last 2 columns all NaNs
m(:, end-1:end) = nan;
%-------------------------------------------------
% Now we have our sample data and we can begin
% Find out where all the NaN's live.
% This is a 2D map of their locations.
nanMap = isnan(m);
% Find out which columns have no NaNs at all.
noNanRows = find(all(~nanMap));
% Find out which columns have all 8760 value = NaN.
allNanRows = find(all(nanMap));
% Find out which columns have NOT all 8760 values = NaN,
% in other words, columns that have at least some values that are not NaNs.
% This is, a mixture of NaN's and valid numerical values.
nansPerColumn = sum(nanMap);
someNanRows = find(nansPerColumn > 0 & nansPerColumn < size(m, 1));

カテゴリ

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