Fill gaps with zeros in a non-consecutive time series

조회 수: 3 (최근 30일)
penny
penny 2017년 12월 18일
댓글: penny 2018년 1월 19일
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