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

4 views (last 30 days)
Mr M.
Mr M. on 2 Oct 2018
Edited: Bruno Luong on 2 Oct 2018
What is the simplest way to extract lengths of NaN sequences from a vector? Plus the indices of their locations!

Accepted Answer

John D'Errico
John D'Errico on 2 Oct 2018
Edited: John D'Errico on 2 Oct 2018
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

More Answers (1)

Bruno Luong
Bruno Luong on 2 Oct 2018
Edited: Bruno Luong on 2 Oct 2018
% a is the input vector
b = isnan(a);
counts = sum(b);
positions = find(b);
  3 Comments
Bruno Luong
Bruno Luong on 2 Oct 2018
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

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!