hgu*_*294 3 matlab interpolation
我有一个包含时间序列的向量,其中包含不同的值和一些设置为零的缺失值:
X=[0,0,2,0,5,0,0,0,4,0];
Run Code Online (Sandbox Code Playgroud)
我想创建一个新的向量,其中缺少值(零)由前一个值填充(如果存在),以便我得到一个新的向量,如下所示:
Z=[0,0,2,2,5,5,5,5,4,4];
Run Code Online (Sandbox Code Playgroud)
我一直在浏览Matlab帮助和这样的论坛,以找到一个整洁而合适的功能,可以通过一行解决方案或类似解决方案,但我没有这样做.我可以通过以下几个不同的步骤解决问题,但我猜测必须有更好更容易的解决方案吗?
当前解决方案
X=[0,0,2,0,5,0,0,0,4,0];
ix=logical(X);
Y = X(ix);
ixc=cumsum(ix);
Z=[zeros(1,sum(~logical(ixc))) Y(ixc(logical(ixc)))];
Run Code Online (Sandbox Code Playgroud)
这样就可以了,但对于一个简单的问题来说,它似乎是一个过于复杂的解决方案,所以任何人都可以帮助我找到更好的问题吗?谢谢.
这是一个使用cumsum的更简单的版本:
X=[0,0,2,0,5,0,0,0,4,0];
%# find the entries where X is different from zero
id = find(X);
%# If we want to run cumsum on X directly, we'd
%# have the problem that the non-zero entry to the left
%# be added to subsequent non-zero entries. Thus,
%# subtract the non-zero entries from their neighbor
%# to the right
X(id(2:end)) = X(id(2:end)) - X(id(1:end-1));
%# run cumsum to fill in values from the left
Y = cumsum(X)
Y =
0 0 2 2 5 5 5 5 4 4
Run Code Online (Sandbox Code Playgroud)