Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: if statements - drastic difference in running time
Date: Thu, 22 Mar 2012 12:46:11 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 26
Message-ID: <jkf6uj$ni$1@newscl01ah.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: www-03-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: newscl01ah.mathworks.com 1332420371 754 172.30.248.48 (22 Mar 2012 12:46:11 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Thu, 22 Mar 2012 12:46:11 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 3395493
Xref: news.mathworks.com comp.soft-sys.matlab:761827

Hi,
I have encountered the following odd behavior I have no explanation for:
In the following code snippet I observe dramatically different running times, depending on the usage of the if statements, which both give the same results. The if query 2 takes about ten times longer than the if query 2.
Has anyone an explanation for this? I run the code on Matlab 7.8.0.347 (R2009a).

tic;

r_array = rand(10,1);
for i=1:10
    r1 = r_array(i);
    r2 = rand(1);
    T = 0;
    for j=1:1000000
        T = T + 0.000001;
         if r1<T        % if query 1
%      if r2<T        % if  query 2
             display(i);
             break
         end
    end
end

toc;

Thank you,
MaxEOE