Path: news.mathworks.com!not-for-mail
From: "James Wright" <jameswright1001@yahoo.co.uk>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Help speeding up/replacing loops
Date: Wed, 17 Jun 2009 16:07:02 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 23
Message-ID: <h1b4b6$nsl$1@fred.mathworks.com>
References: <h18ge7$gta$1@fred.mathworks.com> <h1ao8t$r0f$1@fred.mathworks.com> <h1apo1$kjc$1@gemini.csx.cam.ac.uk> <h1b09q$ngk$1@fred.mathworks.com> <h1b1j5$kks$1@fred.mathworks.com>
Reply-To: "James Wright" <jameswright1001@yahoo.co.uk>
NNTP-Posting-Host: webapp-05-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1245254822 24469 172.30.248.35 (17 Jun 2009 16:07:02 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Wed, 17 Jun 2009 16:07:02 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1878517
Xref: news.mathworks.com comp.soft-sys.matlab:548353


"Matt Fig" <spamanon@yahoo.com> wrote in message <h1b1j5$kks$1@fred.mathworks.com>...
> I don't see an easy vectorization of this snippet.  However, I am wondering why you have not taken the good advice to pre-allocate your arrays before the loops?  This can lead to speed increases which rival those of vectorization in some cases!  For example, put this in a file and run the file:
> 
> 
> clear
> N = 10000;
> 
> tic
> B(1) = 1;  % No Pre-allocation
> for ii = 2:N
>     B(ii) = ii + ii.^2;
> end
> toc
> 
> tic
> B2 = ones(1,N);  % Pre-allocation
> for jj = 2:N
>    B2(jj) = jj + jj.^2; 
> end
> toc
> 
> isequal(B,B2)
I already did the pre-allocations, they're just at the very top of the program. I'm foolishly assuming I can pre-allocate them all at the start, would it actually be better to pre-allocate right before the loop?