Tuesday, June 16, 2009

Matlab: vectorize a loop that depends on past info.

OP here.

Q:

Can anybody think of a vectorized solution to the problem below? suppose x(1) ~= 0;

for k = 2:length(x)
if x(k) == 0
x(k) = x(k-1);
end
end


A:

y = find(x);
x1 = x(y(cumsum(x ~= 0)));



Note:
In most cases the for-loop is probably 3-4 times faster than the vectorized code.

2 comments:

Unknown said...

The function filter can sometimes be helpful when calculating a quantity dependent on past information.

Siyi said...

Wow, Loren you are the first guest I've ever had! And You are one of my favorate bloggers, I feel honored!