Can anybody think of a solution to the problem below?
x is a vector containing real numbers being x(1) <> 0;
I want to vectorize the following loop:
for i = 2: length( x )
if x(i) ==0
x(i) = x( i - 1);
end
end
thanks,
Alexandre
One solution:
y = find(x);
x1 = x(y(cumsum(x ~= 0)))
Not sure it will be faster, but here is vectorized
z = x==0;
nz=find(~z);
z=find(z);
[trash loc]=histc(z,[nz length(x)+1]);
x(z) = x(nz(loc))
% Bruno
Neat!
Bruno
Bruno
Use FIND and CUMSUM. For a ND-vectorized solution that can handle NaN's as well , see:
http://www.mathworks.com/matlabcentral/fileexchange/19906
Jos
I agree, Bruno.
Siyi, your solution was very good and fast. It seems exactly what I was looking for.