在 MATLAB 中用以下非零值替换零

Replace zeros with following nonzero value in MATLAB

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

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 替换为最接近的非零值?

您只需将代码应用到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 版本中,您可以在 cumsum 中使用 'reverse' 标志:

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).';