Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Speed up of for loop
Date: Thu, 19 Jan 2012 18:03:10 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 39
Message-ID: <jf9lsu$67n$1@newscl01ah.mathworks.com>
References: <jf8p66$11t$1@newscl01ah.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: www-05-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: newscl01ah.mathworks.com 1326996190 6391 172.30.248.37 (19 Jan 2012 18:03:10 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Thu, 19 Jan 2012 18:03:10 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: news.mathworks.com comp.soft-sys.matlab:755172

"Norman F." wrote in message <jf8p66$11t$1@newscl01ah.mathworks.com>...
> % Variables
> x=0:0.001:1;
> tau=0.1:0.01:0.3;
> b=rand(length(tau),1);
> n=length(x);
> m=length(tau);
> 
> A = ones(1,m);
> A(1)=0.5; A(m)=0.5;
> A = A*x(2);
> 
> % preallocate iComp
> iComp=zeros(n,1);
> 
> % computation
> for l = 1:n
>   integrand = b.*exp(-x(l)./tau');
>   iComp(l) = A * integrand;
> end
> 
> Is there some way to avoid the for loop? I tryied arrayfun but it was twice as slow as the for loop...
- - - - - - - - -
  There's no need to multiply by A each of those thousand times.  Instead, make the appropriate adjustment in b ahead of time.

% Variables (as before)
x=0:0.001:1;
tau=0.1:0.01:0.3;
b=rand(length(tau),1);
n=length(x);
m=length(tau);

% An alternative
b2 = b/1000; b2([1,m]) = b2([1,m])/2;
iComp = exp((-x).'*(1./tau))*b2;

  I doubt that this will prove to be very much faster though, because the main computational cost is probably the taking of the exponential function some 20000-odd times.  However you can try it and see.

Roger Stafford