Jack
Jack

Reputation: 115

Vectorizing a for-loop operation

I have an SDE I'm approximating by a numerical scheme using this code:

mu = 1.5;
Sigma = 0.5;
TimeStep = 0.001;
Time = 0:TimeStep:5;
random1 = normrnd(2,0.05,[1,500]);
random2 = randn(1,length(Time));
X = zeros(500, length(Time));

for j = 1:500
   X(j,1)= random1(j);
   for i = 1:length(Time)
        X(j,i+1) = X(j,i) - mu*X(j,i)*TimeStep + Sigma*sqrt(2*mu)*sqrt(TimeStep)*random2(i);
   end
end

How would it be possible to remove the outer for-loop and vectorize, so that at each time step, the first value is calculated for all 500 plots?

Upvotes: 0

Views: 40

Answers (1)

HansHirse
HansHirse

Reputation: 18925

That's pretty simple, especially since j is only used for row indexing here:

X(:,1)= random1;
for i = 1:length(Time)
    X(:,i+1) = X(:,i) - mu*X(:,i)*TimeStep + Sigma*sqrt(2*mu)*sqrt(TimeStep)*random2(i);
end

I tested both versions (Octave 5.1.0), and get identical results. Speed-up is about 400x on my machine.

General remark: Never use i and/or j as loop variables, since they are also used as imaginary units, cf. i and j.

Hope that helps!

Upvotes: 1

Related Questions