Fill gaps with zeros in a non-consecutive time series

3 visualizaciones (últimos 30 días)
penny
penny el 18 de Dic. de 2017
Comentada: penny el 19 de En. de 2018
Hi There,
I understand this might be a simple problem, but I have spent a lot of time on it and can't seem to quite figure it out. I have a series of data A: A = [1,1,1,2,3,4,7,7,8,9,9,11,12,16] and want it to look like B: B = [1,1,1,2,3,4,NaN,NaN,7,7,8,9,NaN,11,12,NaN,NaN,NaN,16]
by finding the gaps (e.g. between 4 and 7 or 9 and 11) and fill those with NaNs. While there are a number of elegant solutions for filling gaps in time series, the issue here is that sometimes the numbers are repeating (i.e. as in [1,1,1] or [7,7]) and the gaps are not always 1.
I appreciate any suggestions!

Respuesta aceptada

Greg Dionne
Greg Dionne el 19 de En. de 2018
This should get you started:
function y = pennyanswer(x)
validateattributes(x,{'numeric'},{'row','finite','integer','nondecreasing'})
% build destination index vector
d = diff(x);
d(d==0) = 1;
ivec = cumsum([1 d]);
% build destination vector, y, (pre-populate with NaN).
y = nan(1,ivec(end));
% assign x to proper location in y
y(ivec) = x;
>> pennyanswer([1 1 1 2 3 4 7 7 8 9 9 11 12 16])
ans =
Columns 1 through 18
1 1 1 2 3 4 NaN NaN 7 7 8 9 9 NaN 11 12 NaN NaN
Columns 19 through 20
NaN 16
  1 comentario
penny
penny el 19 de En. de 2018
wow this is great - you make it look easy! I didn't think of using the cumsum function...but that is a good idea. Thanks!!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Programming en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by