Search code examples
matlabfor-loopmatrix-multiplicationmontecarlo

Replacing for loop by matrix multiplication


S= zeros(Sim,n+1);
S(:,1)=S_0;
for i=1:round(n)
     S(:,i+1) = S(:,i) .* cte_exp .* exp(sigma.*sqrt(dt).*normrnd(0,1,Sim,1));
end

I'm trying to rewrite this for loop with matrix operations but the problem is that for every column you need the previous column. Has anyone an idea how to solve this?


Solution

  • Because each column is the element-wise multiplication of the previous column and some new data, you can fill a matrix with the new data only, then use cumprod to apply the multiplication of each column with the previous.

    S = [ S_0 , cte_exp .* exp(sigma.*sqrt(dt).*normrnd(0,1,Sim,round(n))) ];
    S = cumprod(S,2);