How to replace a for loop with something faster
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi,
I have to speed up a portion of my code as much as possible, since the associated computational time is way too high (especially because this part of the code belongs to a nested function, which is called in an optimization process). I 'd like to avoid using a for loop for my vector recursion since its pretty time consuming
I have heard about using the "filter" function or a Cmex file to accelerate the process in a similar discussion (<http://www.mathworks.com/matlabcentral/answers/28396-speed-up-recursive-loop)>, but I dont have a clue of how to apply them to my problem. Therefore, I would really appreciate any kind of help :)
phi=phi'; % the input has to be a row vector
% recursion for calculating A(t,T,Phi)=A_ and B(t,T,Phi)=B_ (see
% p.592 in Heston and Nandi article)
%A=zeros(phi.*r);
row=size(phi,1);
A=zeros(row,T-1);
B=zeros(row,T-1);
A(:,T)=0;
B(:,T)=0;
*for i=1:T-1
A(:,T-i)=A(:,T-i+1)+phi.*r+B(:,T-i+1).*w-.5*log(1-2*a.*B(:,T-i+1));
B(:,T-i)=phi.*(lam_+g_)-.5*g_^2+b.*B(:,T-i+1)+.5.*(phi-g_).^2./(1-2.*a.*B(:,T-i+...
1));
end*
A_=A(:,1)+phi.*r+B(:,1).*w-.5*log(1-2.*a.*B(:,1)); % A(t;T,phi)
B_=phi.*(lam_+g_)-.5*g_^2+b.*B(:,1)+.5*(phi-g_).^2./(1-2.*a.*B(:,1)); % B(t;T,phi)
Thanks a lot!!!
Notes: r w a b lam_ g_ S_0 Sig_ are scalars, phi is a vector that might contain complex numbers
Basically the backward recursion is as described in the for loop, from final conditions A(T,T)=B(T,T)=0
2 commentaires
Simon
le 22 Nov 2013
Hi!
Can you give example values for the parameters so that we can execute the code?
Réponses (2)
Andrei Bobrov
le 22 Nov 2013
Please try is it:
p1 = phi.*r;
p2 = phi.*(lam_+g_)-.5*g_^2;
p3 = .5.*(phi-g_).^2;
a2 = 2*a;
for ii = 1:T-1
k = T-ii+1;
p4 = 1-a2.*B(:,k);
A(:,k-1) = A(:,k) + p1 + B(:,k).*w - .5*log(p4);
B(:,k-1) = p2 + b.*B(:,k) + p3./p4;
end
Simon
le 22 Nov 2013
Hi!
If you don't need the results of every loop, you can write:
p1 = phi.*r;
p2 = phi.*(lam_+g_)-.5*g_^2;
p3 = .5.*(phi-g_).^2;
a2 = 2*a;
A=zeros(row,1);
B=zeros(row,1);
for ii = 1:T-1
p4 = 1-a2*B;
A = A + p1 + B*w - .5*log(p4);
B = p2 + b*B + p3./p4;
end
It saves some more time.
5 commentaires
Simon
le 22 Nov 2013
No, this will give you the independent calculation of A and B, but this is not possible since A depends on B.
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!