replace zero values with previous non-zero values

916 Views Asked by At

I need a fast way in Matlab to do something like this (I am dealing with huge vectors, so a normal loop takes forever!):

from a vector like

[0 0 2 3 0 0 0 5 0 0 7 0]

I need to get this:

[NaN NaN 2 3 3 3 3 5 5 5 7 7]

Basically, each zero value is replaced with the value of the previous non-zero one. The first are NaN because there is no previous non-zero element in the vector.

4

There are 4 best solutions below

3
On BEST ANSWER

Try this, not sure about speed though. Got to run so explanation will have to come later if you need it:

interp1(1:nnz(A), A(A ~= 0), cumsum(A ~= 0), 'NearestNeighbor')
0
On

Just for reference, here are some similar/identical functions from exchange central and/or SO columns.

nearestpoint ,

try knnimpute function.

Or best of all, a function designed to do exactly your task:

repnan (obviously, first replace your zero values with NaN)

3
On

I had a similar problem once, and decided that the most effective way to deal with it is to write a mex file. The c++ loop is extremely trivial. After you'l figure out how to work with mex interface, it will be very easy.

4
On

Try this (it uses the cummax function, introduced in R2014b):

i1 = x==0;
i2 = cummax((1:numel(x)).*~i1);
x(i1&i2) = x(i2(i3));
x(~i2) = NaN;