Path: news.mathworks.com!newsfeed-00.mathworks.com!NNTP.WPI.EDU!elk.ncren.net!newsflash.concordia.ca!canopus.cc.umanitoba.ca!not-for-mail
From: roberson@ibd.nrc-cnrc.gc.ca (Walter Roberson)
Newsgroups: comp.soft-sys.matlab
Subject: Re: A simple question about FOR
Date: Tue, 26 Feb 2008 19:56:15 +0000 (UTC)
Organization: National Research Council Canada - Conseil national de rechereches Canada
Lines: 33
Message-ID: <fq1qsv$ic7$1@canopus.cc.umanitoba.ca>
References: <fq1lcs$t07$1@atlantis.news.tpi.pl>
NNTP-Posting-Host: origin.ibd.nrc.ca
X-Trace: canopus.cc.umanitoba.ca 1204055775 18823 192.70.172.160 (26 Feb 2008 19:56:15 GMT)
X-Complaints-To: abuse@cc.umanitoba.ca
NNTP-Posting-Date: Tue, 26 Feb 2008 19:56:15 +0000 (UTC)
Originator: roberson@ibd.nrc-cnrc.gc.ca (Walter Roberson)
Xref: news.mathworks.com comp.soft-sys.matlab:453845



In article <fq1lcs$t07$1@atlantis.news.tpi.pl>,
Kamil  <milka-wywal@to.free.of.pl> wrote:

>I am wondering, if there was a simple way to suppress 'for' command in 
>MATLAB.
>This would force students to use smarter solutions than just a lot of 
>for loops and waiting :)

Sometimes using a 'for' or 'while' loop *is* the most efficient way.

For example a couple of weeks ago, I had a case in which the
standard matlab method of writing a section of code was roughly

[X,Y] = ndgrid(A,B);
answer = sum(X < Y);

Now allow A and B to grow to roughly 1200 elements each, and
call this code 100,000 times, and these two lines of code took
approximately 26.13 minutes to execute.

After some thought, I replaced this short code with a 'while'
loop that took noticably more coding lines, but was linear in the
size of A (and independant of the size of B). With the same dataset,
calling the same 100,000 times, the replacement code took 2.39 seconds
total to execute.

Now, if I were to turn in that 'while' solution that was ~50 times
faster than anyone else achieved using matlab vectorized operations,
would you fail me on the assignment for not using a sufficiently
"smart" solution?
-- 
  "The beauties of conception are always superior to those of
   expression."                               -- Walter J. Phillips