Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Vectorizing a loop that depens on past information

1 view
Skip to first unread message

Alexandre Velloso

unread,
Jun 14, 2009, 3:19:02 PM6/14/09
to
Hello,

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

Message has been deleted

Siyi

unread,
Jun 14, 2009, 3:46:53 PM6/14/09
to

One solution:

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

Bruno Luong

unread,
Jun 14, 2009, 3:49:01 PM6/14/09
to
"Alexandre Velloso" <aleve...@gmail.com> wrote in message <h13if6$6hr$1...@fred.mathworks.com>...

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

Bruno Luong

unread,
Jun 14, 2009, 3:57:01 PM6/14/09
to
Siyi <Mr.Siy...@gmail.com> wrote in message <bd9d00c3-a148-4d2a-

>
> One solution:
>
> y = find(x);
> x1 = x(y(cumsum(x ~= 0)))

Neat!

Bruno

Bruno Luong

unread,
Jun 14, 2009, 4:19:01 PM6/14/09
to
I have just timed it, for-loop is about 4-5 time faster. I would stick with for-loop solution.

Bruno

Jos

unread,
Jun 14, 2009, 4:25:03 PM6/14/09
to
"Alexandre Velloso" <aleve...@gmail.com> wrote in message <h13if6$6hr$1...@fred.mathworks.com>...

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

Alexandre Velloso

unread,
Jun 14, 2009, 4:40:04 PM6/14/09
to
Thank you, guys.

I agree, Bruno.

Siyi, your solution was very good and fast. It seems exactly what I was looking for.

Alexandre Velloso

unread,
Jun 14, 2009, 5:07:01 PM6/14/09
to
Thank u, Jos.
0 new messages