Path: news.mathworks.com!not-for-mail
From: "Bruno Luong" <b.luong@fogale.findmycountry>
Newsgroups: comp.soft-sys.matlab
Subject: Re: forloop efficiency
Date: Sun, 12 Jul 2009 06:11:03 +0000 (UTC)
Organization: FOGALE nanotech
Lines: 12
Message-ID: <h3bupn$a23$1@fred.mathworks.com>
References: <h3bd1h$86h$1@fred.mathworks.com> <h3bpvt$2c8$1@fred.mathworks.com>
Reply-To: "Bruno Luong" <b.luong@fogale.findmycountry>
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 1247379063 10307 172.30.248.35 (12 Jul 2009 06:11:03 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Sun, 12 Jul 2009 06:11:03 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 390839
Xref: news.mathworks.com comp.soft-sys.matlab:554740


There is no trivial rule about "for-loop" is slow. It is quite hard to judge before hand whereas for-loop or vectorized solution is better. It needs quite a bit of experiences in Matlab in judge well, and even experience users are sometime stumbled.

Few easy tricks come to mind:
- if there is an equivalent vectorized stock function, always use it
- avoid for-loop that call function with non negligible overhead
- for loop is desirable when a nested IF condition can be used to save computation time
- for loop is attractive when the result of the preceding iteration(s) can be used to save computation effort of the current calculation
- using for loop is not recommended when the large data need to be duplicated inside the loop
- time it, time it and time it.
- Read Matt Fig's post!

Bruno