在MATLAB中将零替换为以下非零值

时间:2017-12-04 18:02:03

标签: matlab replace zero

我有一个向量A,其中包含zeros的值。我现在想用以下非零值替换所有zeros。我发现这个solution by @Luis Mendo用以前的非零值替换零。

A = [1 0 2 0 7 7 7 0 5 0 0 0 9];
t = cumsum(A~=0);
u = nonzeros(A);
B = u(t).';

是否有类似的方法将zeros替换为最接近的非零值?

1 个答案:

答案 0 :(得分:2)

您只需将代码应用于A的翻转版本,然后翻转结果:

A = [1 0 2 0 7 7 7 0 5 0 0 0 9];
t = cumsum(flip(A)~=0);
u = nonzeros(flip(A));
B = flip(u(t).');

或者,如@craigim所述,在最近的Matlab版本中,您可以使用'reverse'中的cumsum标记:

A = [1 0 2 0 7 7 7 0 5 0 0 0 9];
t = cumsum(A ~= 0, 'reverse');
u = nonzeros(flip(A));
B = u(t).';