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

1 visualización (últimos 30 días)
What is the simplest way to extract lengths of NaN sequences from a vector? Plus the indices of their locations!

Respuesta aceptada

John D'Errico
John D'Errico el 2 de Oct. de 2018
Editada: John D'Errico el 2 de Oct. de 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

Más respuestas (1)

Bruno Luong
Bruno Luong el 2 de Oct. de 2018
Editada: Bruno Luong el 2 de Oct. de 2018
% a is the input vector
b = isnan(a);
counts = sum(b);
positions = find(b);
  3 comentarios
Mr M.
Mr M. el 2 de Oct. de 2018
No, I want to count sequences! not single elements!
Bruno Luong
Bruno Luong el 2 de Oct. de 2018
Editada: Bruno Luong el 2 de Oct. de 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

Iniciar sesión para comentar.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by