Fill gaps with zeros in a non-consecutive time series

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

采纳的回答

Greg Dionne
Greg Dionne 2018-1-19
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 个评论
penny
penny 2018-1-19
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!!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by