From: Raul on
Hi all,

I am trying to vectorize a piece of code with nested loops, but I seem to be getting it always wrong. Can anyone think of a way to eliminate the two nested loops in the code below? I am trying to compute a matrix M, and all things on the right-hand side like valFuncSigma, M_0v, M2_S and so on used to calculate the matrix M are not functions, but matrices that have previously been computed. Here's the code:

bb = 1:N_v;
aa = 1:N_v;
for jj = 1:N_S
SS = (jj-1)/2^JS;
for kk = 1:N_S

M((jj-1)*N_v+aa,(kk-1)*N_v+bb) = ...

0.5*repmat(valFuncSigma(aa),1,N_v).*(SS^2*M_2S(jj,kk)*M_0v(aa,bb)) ...
+rho*sqrt(abs(repmat(valFuncSigma(aa),1,N_v).*repmat(valFuncVoVol(aa),1,N_v))).* (SS* M_1S(jj,kk)*M_1v(aa,bb)) ...

+ (r-div)*SS*M_1S(jj,kk)*M_0v(aa,bb) ...

+ 0.5*(repmat(valFuncVoVol(aa),1,N_v)).*(M_0S(jj,kk)*M_2v(aa,bb)) ...

+ repmat(valFuncVolDrift(aa),1,N_v).*M_0S(jj,kk)*M_1v(aa,bb)) ...
- r * M_0S(jj,kk)*M_0v(aa,bb);
end
end

Thanks!

--Raul