Joe
Joe

Reputation: 453

Replace zeros with following nonzero value in MATLAB

I have a vector A, which contains values that are zeros. I would now like to replace all zeros with the following non-zero value. I found this solution by @Luis Mendo to replace zeros with the previous non-zero values.

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

Is there a similar way to replace the zeros with the closest following non-zero value as well?

Upvotes: 0

Views: 180

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

You only need to apply the code to a flipped version of A and then flip the result:

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

Or, as noted by @craigim, in recent Matlab versions you can use the 'reverse' flag in 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).';

Upvotes: 2

Related Questions