Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Speed up of for loop

Subject: Speed up of for loop

From: Norman Fuhrmann

Date: 19 Jan, 2012 09:53:10

Message: 1 of 3

hey,

I am trying to speed up a part of my code:

% 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...

Thanks in advance,
Norman

Subject: Speed up of for loop

From: Roger Stafford

Date: 19 Jan, 2012 18:03:10

Message: 2 of 3

"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

Subject: Speed up of for loop

From: Roger Stafford

Date: 22 Jan, 2012 19:36:27

Message: 3 of 3

"Roger Stafford" wrote in message <jf9lsu$67n$1@newscl01ah.mathworks.com>...
> b2 = b/1000; b2([1,m]) = b2([1,m])/2;
- - - - - - -
  I should have written b2 = b*x(2); instead of b2 = b/1000;

Roger Stafford

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us