필터 지우기
필터 지우기

Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

Can I avoid this slow for loop?

조회 수: 1 (최근 30일)
Filippo
Filippo 2015년 8월 21일
마감: MATLAB Answer Bot 2021년 8월 20일
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

답변 (1개)

Varun Bhaskar
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
Varun Bhaskar
Varun Bhaskar 2015년 8월 25일
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!

Translated by