Info

This question is closed. Reopen it to edit or answer.

Can I avoid this slow for loop?

2 views (last 30 days)
Filippo
Filippo on 21 Aug 2015
Closed: MATLAB Answer Bot on 20 Aug 2021
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

Answers (1)

Varun Bhaskar
Varun Bhaskar on 25 Aug 2015
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 Comment
Varun Bhaskar
Varun Bhaskar on 25 Aug 2015
This would improve execution time significantly.

Community Treasure Hunt

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

Start Hunting!