Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: forloop efficiency
Date: Sun, 12 Jul 2009 01:08:01 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 23
Message-ID: <h3bd1h$86h$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1247360881 8401 172.30.248.37 (12 Jul 2009 01:08:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Sun, 12 Jul 2009 01:08:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1646679
Xref: news.mathworks.com comp.soft-sys.matlab:554724


I've been told to avoid forloops in matlab because they're extremely slow.
consider this:

clear('cap')
tic;
cap=ones(15,1);
for i=1:15
    cap(i)=2;
end
toc;

clear('cap')
tic;
cap=ones(15,1);
cap(:)=2;
toc;
%%


Elapsed time is 0.000088 seconds.
Elapsed time is 0.000017 seconds.

What is matlab DOING when we do cap(:)=2, is it not a for loop ?? it's more than 4x faster than a for loop.