Path: news.mathworks.com!not-for-mail
From: "Steven Lord" <slord@mathworks.com>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Help speeding up/replacing loops
Date: Tue, 16 Jun 2009 23:24:50 -0400
Organization: The MathWorks, Inc.
Lines: 46
Message-ID: <h19nl1$in$1@fred.mathworks.com>
References: <h18ge7$gta$1@fred.mathworks.com> <h18irl$1um$1@fred.mathworks.com> <h18kfh$j71$1@fred.mathworks.com>
Reply-To: "Steven Lord" <slord@mathworks.com>
NNTP-Posting-Host: lords.dhcp.mathworks.com
X-Trace: fred.mathworks.com 1245209057 599 144.212.105.187 (17 Jun 2009 03:24:17 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Wed, 17 Jun 2009 03:24:17 +0000 (UTC)
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 6.00.2900.5512
X-RFC2646: Format=Flowed; Original
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.5579
Xref: news.mathworks.com comp.soft-sys.matlab:548154



"James Wright" <jameswright1001@yahoo.co.uk> wrote in message 
news:h18kfh$j71$1@fred.mathworks.com...
> "Steven Lord" <slord@mathworks.com> wrote in message 
> <h18irl$1um$1@fred.mathworks.com>...

*snip*

> MLINT does flag them up and say that I should take them out of the loops, 
> but that's what I'm unsure how to do. I've done it for simple things like 
> C(1:g) = (rand(1)*pi); but I'm unsure how to do it for loops like:
>
> p(1) = B(1)*cos(C(f));
> q(1) = B(1)*sin(C(f));
> for n = 2:N
>      p(n) = p(n-1) + B(n)*cos(n*C(f));
>      q(n) = q(n-1) + B(n)*sin(n*C(f));
> end
>
> where previous values in the vector are used to calculate the new one

You may not need to vectorize this at all if you preallocate.  To 
preallocate, just put values into the array before the loop until it's the 
size that it will need to be in the end.

p = zeros(1, N);
q = zeros(1, N);
p(1) = B(1)*cos(C(f));
q(1) = B(1)*sin(C(f));
for n = 2:N
     p(n) = p(n-1) + B(n)*cos(n*C(f));
     q(n) = q(n-1) + B(n)*sin(n*C(f));
end

Now instead of growing the p and q arrays inside the loop (making it 2 
elements long, then 3, then 4, etc.) you're just filling them in.  That 
means no memory growing inside the loop, so it'll be faster.

If preallocation doesn't improve performance enough, then you can continue 
on to vectorization using CUMSUM as Matt suggested.

-- 
Steve Lord
slord@mathworks.com