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

1 次查看(过去 30 天)
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

更多回答(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 个评论
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 CenterFile Exchange 中查找有关 NaNs 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by