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

Optimizing a loop

1 view
Skip to first unread message

Chris de Bleu

unread,
Jul 24, 2009, 4:39:02 PM7/24/09
to
Hi,

Is there a manner to optimize (vectorize) this loop?

fval = 0
for i = 1:N
for j = i+1:N
z = y(i) - y(j) ;
fval = fval + z*z ;
end
end
fval = 2*fval

It is computing \sum_{i=1}^{N} \sum_{j=1}^{N} (x(i) - x(j))^2.

Thanks,

Chris

Alan

unread,
Jul 24, 2009, 5:32:02 PM7/24/09
to
"Chris de Bleu" <blue...@yahoo.fr> wrote in message <h4d655$8bk$1...@fred.mathworks.com>...

One way is with meshgrid and sum:

X = meshgrid(x);
f = sum(sum((X - X.').^2));

Matt Fig

unread,
Jul 24, 2009, 9:13:01 PM7/24/09
to
"Alan " <mongui...@OVETHIS.yahoo.com> wrote in message <h4d98i$puh$1...@fred.mathworks.com>...

> "Chris de Bleu" <blue...@yahoo.fr> wrote in message <h4d655$8bk$1...@fred.mathworks.com>...
> > Hi,
> >
> > Is there a manner to optimize (vectorize) this loop?

Just a note, optimize and vectorize are not the same thing. See the many recent posts on here where For loops crushed all comers in speed. Any given vectorization may or may not be faster than a well written For loop.

> > fval = 0
> > for i = 1:N
> > for j = i+1:N
> > z = y(i) - y(j) ;
> > fval = fval + z*z ;
> > end
> > end
> > fval = 2*fval
> >
> > It is computing \sum_{i=1}^{N} \sum_{j=1}^{N} (x(i) - x(j))^2.
> >
> > Thanks,
> >
> > Chris
>
> One way is with meshgrid and sum:
>
> X = meshgrid(x);
> f = sum(sum((X - X.').^2));


You could vectorize this with bsxfun, but I think your For loop is going to beat it in speed. The above solution (with meshgrid) is certainly slower and uses more memory.

Siyi Deng

unread,
Jul 24, 2009, 10:00:26 PM7/24/09
to
Hey, I think this particular loop is quit optimizable:

suppose y is column vector (if not, columnize it)
this line will do the job:

f = 2*((n+1)*sum(y.^2)-2*cumsum(y')*y);


Crystal

unread,
Jul 27, 2009, 3:06:13 PM7/27/09
to
On Jul 24, 7:00 pm, Siyi Deng <mr.siyi.d...@gmail.com> wrote:
> Hey, I think this particularloopis quit optimizable:

>
> suppose y is column vector (if not, columnize it)
> this line will do the job:
>
> f = 2*((n+1)*sum(y.^2)-2*cumsum(y')*y);

This seems to work, but could somebody please explain what happend?

someone

unread,
Jul 27, 2009, 3:29:03 PM7/27/09
to
Crystal <aro...@gmail.com> wrote in message <5262b8f0-15cc-47c7...@j9g2000prh.googlegroups.com>...

doc cumsum
doc sum

What else do you need to know?

0 new messages