MATLAB: How to change the value of zeros to first nonzero number below it

change valuesnon-zeroszeros

I have a column vector with tens of thousands of entries, and most of these entries are zeros. I am trying to find the most concise code to change the values of zero to the first nonzero value below that particular zero.
Example:
If I have:
A = [0; 0; 15; 0; 0; 0; 5; 0; 0; 0; 0; 0; 3; 0; 0; 0; 0; 9]
Then I would want
A = [15; 15; 15; 5; 5; 5; 5; 3; 3; 3; 3; 3; 3; 9; 9; 9; 9; 9]
Thank you for any help!

Best Answer

This works:
A = [0; 0; 15; 0; 0; 0; 5; 0; 0; 0; 0; 0; 3; 0; 0; 0; 0; 9];
IxVct = [0; find(diff([0; A]) > 0)];
for k1 = 1:length(IxVct)-1
Ix = [IxVct(k1)+1 IxVct(k1+1)];
B(Ix(1):Ix(2),:) = A(Ix(2))*ones(diff(Ix)+1,1);
end