Info
此问题已关闭。 请重新打开它进行编辑或回答。
Can I avoid this slow for loop?
1 次查看(过去 30 天)
显示 更早的评论
I am writing a program to compute a value function which is defined over a 3 dimensional state space. It's a dynamic programming problem which I have managed to reduce to 2 control variables. The code works, but every iteration takes about 1 minute and it takes about 100 iterations to reach convergence. Is there a simple way to get rid of the "for" loop and vectorize also that part of the code? Thanks
%STATE SPACE;
mu=(0.01:0.01:.9);
b=-3:.05:0;
delta=0.01:0.05:1.2;
[DELTA,B,MU]=meshgrid(delta,b,mu);
iter=1;
norm=1001;
tol=.001;
% Initial Guess for Value Function
V0=0.*DELTA;
%Control variables grid
y=[ya:0.05:yb];
[CA,CB]=meshgrid(y,y);
iter=1;
norm=1001;
tol=.01;
%Main loop
while norm>tol
for i=1:length(mu)
for j=1:length(b)
for z=1:length(delta)
dp=f(mu(i),b(j),delta(z),CB,CA);
bp=g(mu(i),b(j),delta(z),CB,CA);
mup=h(mu(i),b(j),delta(z),CB,CA);
fval= l(mu(i),CA,CB)+beta*interp3(DELTA,B,MU,V0,dp,bp,mup,'linear');
[mr mc]=find(fval==max(max(fval)));
V1(j,z,i)=fval(mr(1),mc(1));
end
end
end
toc
norm(iter)=max(max(max(abs(V0-V1))))
V0=V1;
iter=iter+1
end
0 个评论
回答(1 个)
Varun Bhaskar
2015-8-25
Hi Filippo,
You can parallelize your code to be executed on different cores on your machine. You can find more information about the 'parfor' loop construct in the following link :
1 个评论
此问题已关闭。
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!