Reputation: 291
I am running a Monte-Carlo simulation to calculate Y such as: Y(i,j+1)=Y(i,j)*a(i,j)+b
I would like to avoid when possible the use of for loop, and use instead matrix computation as it's the advantage of Matlab.
Here is my code:
kappa = 6.21;
theta = 0.019;
sigma = 0.61;
rho = -0.7;
r = 0.0319;
V0 = 0.010201;
T = 1;
N = 300; % Time steps
M = 1e6; % Number of simulations
dt = T/N;
Z = randn(M,N);
a = kappa*dt+sigma*sqrt(dt);
b = kappa*theta*dt;
% With loop
tic
y = zeros(M,N); % preallocate
y(:,1) = V0; % initial value
for i=1:M
for j = 1:N
y(i,j+1) = y(i,j)*(1-a*Z(i,j))+b;
end
end
toc
This is a small part of my entire code and alone it takes 65 seconds to run for the given parameters. Is there a way to make it faster, by doing matrix computation instead of loops? Thank you
Upvotes: 1
Views: 184
Reputation: 772
Seems like, every column is dependent on the previous column values except the 1st column. So, you could get rid of the first for-loop by doing something similar to the following:
for j=2:N
y(:,j) = y(:,j-1).*(1-a*Z(:,j-1)) + b;
end
This one reduces the time by almost half.
Upvotes: 2