How to replace a for loop with something faster

1 次查看(过去 30 天)
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 个评论
Simon
Simon 2013-11-22
Hi!
Can you give example values for the parameters so that we can execute the code?
Maël
Maël 2013-11-22
Sure:
a= 1.32e-6; b= 0.589; lam_= -0.5; g_= 422.0950; w=5.02e-6 T= 60;S_0= 1132.60;Sig_=1.4416e-04;r=6.6048e-05;
phi= [-79.6315i; -93.2105i]
Thanks a lot for your help Simon!

请先登录,再进行评论。

回答(2 个)

Andrei Bobrov
Andrei Bobrov 2013-11-22
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
Simon 2013-11-22
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 个评论
Simon
Simon 2013-11-22
No, this will give you the independent calculation of A and B, but this is not possible since A depends on B.
Maël
Maël 2013-11-22
You're absolutely right, it missed that.. Thank you for your help!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by