MATLAB: Replace zeros in a vector with previous nonzero number

replace; zeros

Hi all,
I have a vector 1 by 400 consisting of nonzero numbers and zeros. I want to create a new vector that fills the zeros positions with the latest previous nonzero number. Ex. A=[12 15 42 65 0 133 15 0 0 16] must be turned into B=[12 15 42 65 65 133 15 15 15 16] thanks a lot! Here is a code which gives me error
[PnLFlow]=PnLFlow(PnL_Aggregate)
for u=1:length(PnL_Aggregate(:,1))
while PnL_Aggregate(u,1) ~= 0
PnLFlow(u,1) = PnL_Aggregate(u,1)
if PnLFlow(u)=PnL_Aggregate(find(PnL_Aggregate(1:u,1),1,'last'))
end
pause
end
end

Best Answer

I did not try to find the error in your attempted solution.
Here is a simpler for loop:
for ia = 2:numel(A)
if A(ia) == 0
A(ia) = A(ia-1);
end
end