Path: news.mathworks.com!newsfeed-00.mathworks.com!newsfeed2.dallas1.level3.net!news.level3.com!postnews.google.com!news1.google.com!newsfeed.stanford.edu!shelby.stanford.edu!not-for-mail
From: "Linus Utopia" <linus_utopia@gmail.com>
Newsgroups: comp.soft-sys.matlab
Subject: How to vectorize and avoid this for loop to speed up?
Date: Wed, 25 Jul 2007 00:07:41 -0400
Lines: 38
Message-ID: <f86ief$f4n$1@news.Stanford.EDU>
X-Trace: news.Stanford.EDU 1185336591 15511 127.0.0.1 (25 Jul 2007 04:09:51 GMT)
X-Complaints-To: news@news.stanford.edu
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 6.00.2900.3138
X-MIMEOLE: Produced By Microsoft MimeOLE V6.00.2900.3138
X-RFC2646: Format=Flowed; Original
Xref: news.mathworks.com comp.soft-sys.matlab:420879



Hi all,

When inside a loop, there is a vector operator(r and p) already, how to 
further vectorize it along another dimension (for "u" and "us")?

Here is my code:

---------------

tmp=zeros(size(us));  %pre-allocation
for i=1:length(us);
    u=us(i);
    t7=u+b*p(:);
    tmp(i)=exp(-u*a- r(:).'*t7(:) );
end;

---------------

Let me explain. "us" is a vector. I generate "tmp" the same length as "us".

For each element of "us", I compute an element for "tmp".

"p" and "r" are vectors of equal length.

"a" and "b" are scalars and constants.

r(:).'*t7(:)  is the dot-product of two vectors and hence it is a scalar.

Hence each tmp(i) is a scalar.

Is there a way to vectorize the above for loop?

I have been pondering on this for long time but I am not that creative, or 
perhaps is lack of experience, etc. I couldn't come up with a good idea...

Thanks!