How can I make this code more efficient?
Ältere Kommentare anzeigen
close; clear all; clc;
global cp1 vp1 cp2 vp2 value gk;
A=1; % aggregate productivity
a=0.36; % capital share of output (alpha)
b=0.96; % subjective discounting (beta)
d=0.069;% depreciation
klow=0.1;
khigh=6;
knum=250;
kgrid = linspace(klow,khigh,knum);
uf = @(x)log(x);
pf = @(x)(A*(x.^a));
cp2=[cp2,pf(kgrid(1:knum))+((1-d)*kgrid(1:knum))]; %period 2
vp2=[vp2,uf(cp2(1:knum))];
for i=1:knum %period 1
for j=1:knum
cp1(i,j)=max(pf(kgrid(i))+(1-d)*kgrid(i)-kgrid(j),0);
vp1(i,j)= log(cp1(i,j))+(b*vp2(j));
end
value=[value,max(vp1(i,:))];
[val,loc] = max(vp1(i,:));
gk=[gk,kgrid(loc)];
end
figure
subplot(211)
plot(kgrid, value)
hold on
title ( ' the value function ' )
subplot(212)
plot(kgrid, kgrid)
hold on
plot(kgrid, gk, '*')
title ( ' the decision rule ' )
saveas(gcf,'optimal2.png')
What can I do to make this code take up less lines or compute faster?
2 Kommentare
jahanzaib ahmad
am 17 Feb. 2019
no one gona help this way .please write what this code is about . edit ur title
"What can I do to make this code take up less lines or compute faster?"
- Write functions instead of scripts.
- Get rid of pointless cargo-cult programming close, clear all, and clc.
- Get rid of global variables and pass data properly as input/output arguments.
- Preallocate the output array/s before the loops, do not grow them inside the loops.
- Read and understand the techniques explained in the documentation:
- Use the profiler to identify which lines take the most time, then get back to us:
Antworten (0)
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!