لم تعُد "مجموعات Google" تتيح المشاركات أو الاشتراكات الجديدة من Usenet. وسيبقى بالإمكان عرض المحتوى السابق.

Optimizing a loop

مرّة مشاهدة واحدة
التخطي إلى أول رسالة غير مقروءة

Chris de Bleu

غير مقروءة،
24‏/07‏/2009، 4:39:02 م24‏/7‏/2009
إلى
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

غير مقروءة،
24‏/07‏/2009، 5:32:02 م24‏/7‏/2009
إلى
"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

غير مقروءة،
24‏/07‏/2009، 9:13:01 م24‏/7‏/2009
إلى
"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

غير مقروءة،
24‏/07‏/2009، 10:00:26 م24‏/7‏/2009
إلى
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

غير مقروءة،
27‏/07‏/2009، 3:06:13 م27‏/7‏/2009
إلى
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

غير مقروءة،
27‏/07‏/2009، 3:29:03 م27‏/7‏/2009
إلى
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 رسالة جديدة