What is the simplest way to extract lengths of NaN sequences from a vector?

1 回表示 (過去 30 日間)
Mr M.
Mr M. 2018 年 10 月 2 日
編集済み: Bruno Luong 2018 年 10 月 2 日
What is the simplest way to extract lengths of NaN sequences from a vector? Plus the indices of their locations!

採用された回答

John D'Errico
John D'Errico 2018 年 10 月 2 日
編集済み: John D'Errico 2018 年 10 月 2 日
Given sequences in a vector of NaNs, you find the location of the start, then find the end. the length is given by the difference. So how do you do it? SIMPLE. Use string search tools.
S = 1:100;
S(rand(size(S)) > .5) = NaN;
So roughly 50% NaNs. I'd bet there are some sequences in there.
Nanstart = strfind([0,isnan(S)],[0 1]);
Nanend = strfind([isnan(S),0],[1 0]);
The length of each sequence is just 1 more than the difference.
Nanlength = Nanend - Nanstart + 1;
S
S =
Columns 1 through 31
NaN 2 NaN 4 5 NaN 7 8 NaN NaN NaN NaN NaN NaN 15 16 NaN NaN 19 NaN NaN 22 23 NaN 25 NaN 27 28 29 30 31
Columns 32 through 62
32 NaN NaN NaN NaN 37 NaN NaN NaN 41 42 43 NaN 45 NaN 47 48 49 NaN NaN NaN NaN 54 NaN NaN 57 58 59 60 61 NaN
Columns 63 through 93
63 NaN 65 NaN 67 NaN 69 70 NaN 72 73 NaN 75 NaN 77 NaN NaN NaN 81 82 NaN 84 85 86 NaN 88 89 NaN 91 NaN NaN
Columns 94 through 100
94 NaN NaN NaN 98 NaN NaN
Nanstart
Nanstart =
1 3 6 9 17 20 24 26 33 38 44 46 50 55 62 64 66 68 71 74 76 78 83 87 90 92 95 99
Nanlength
Nanlength =
1 1 1 6 2 2 1 1 4 3 1 1 4 2 1 1 1 1 1 1 1 3 1 1 1 2 3 2
  2 件のコメント
Mr M.
Mr M. 2018 年 10 月 2 日
no tricky effects on the ends?
Bruno Luong
Bruno Luong 2018 年 10 月 2 日
No

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

その他の回答 (1 件)

Bruno Luong
Bruno Luong 2018 年 10 月 2 日
編集済み: Bruno Luong 2018 年 10 月 2 日
% a is the input vector
b = isnan(a);
counts = sum(b);
positions = find(b);
  3 件のコメント
Mr M.
Mr M. 2018 年 10 月 2 日
No, I want to count sequences! not single elements!
Bruno Luong
Bruno Luong 2018 年 10 月 2 日
編集済み: Bruno Luong 2018 年 10 月 2 日
Sorry, for sequence:
b = isnan(a(:)');
d = diff([0 b 0]);
i1 = find(d==1);
i9 = find(d==-1)-1;
if ~isempty(lgt)
fprintf('nan from (%d,%d)\n', [i1;i9]);
end

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

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by