Fill gaps with zeros in a non-consecutive time series

2 views (last 30 days)
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!

Accepted Answer

Greg Dionne
Greg Dionne on 19 Jan 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 Comment
penny
penny on 19 Jan 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!!

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!