I need help with running two for loops

조회 수: 1 (최근 30일)
Ali Mara
Ali Mara 2021년 3월 1일
댓글: Walter Roberson 2021년 3월 1일
So I have to rewrite a code, I can do it the hard way manually input each sigma value but I prefer to do it more elegantlly ,I want to create a vector with the five values of sigma and create two matrices one for k and c with five columns. The problem I am having is that it is running through first iteration j=1 , but not running after that. This is what I have so far.
% Parameter values
A = 1;
alpha = .3;
beta = 0.96;
delta = 0.08;
lambda = .1;
%sigma = 1.01;%
sigma=[01,1.01,2,3,4];
% Steady state
kss = (1/(A*alpha)*(1/beta-(1-delta)))^(1/(alpha-1));
css = A*kss^alpha-delta*kss;
% Initial stock of capital
k0 = lambda*kss;
% Number of periods
T = 200;
% Initialize vectors
c = zeros(T,length(sigma));
k = zeros(T,length(sigma));
% Pick range for c in first period
cmin = 0;
cmax = A*k0^alpha+(1-delta)*k0;
for j=1:length(sigma)
% Guess that c(1) will be the average of the cmax and cmin
c(1,j) = (cmax+cmin)/2;
% Populate the capital stock in period 1
k(1,j) = k0;
end
% Technical parameters
tol = 1e-5;
dif = 1;
for j=1:length(sigma)
while dif > tol
for t = 2:T
k(t,j) = A*k(t-1,j).^alpha + (1-delta).*k(t-1,j) - c(t-1,j); % Given c(t-1), compute k(t) from feasibility
c(t,j) = (beta.*c(t-1,j)^sigma(j).*(alpha.*A*k(t,j).^(alpha-1)+1-delta))^(1/sigma(j)); % Given c(t-1), compute c(t) from Euler
if (k(t,j)<k(t-1,j)) % If k starts dropping, then the guess for c(2) was too high. Reduce it.
cmax = c(1,j); % Reduce upper bound for c(1) to what we chose before
c(1,j) = (cmax+cmin)/2;% New choice for c(1)
break % Exit the for loop and start again.
elseif k(t,j)>kss% If k becomes larger than kss, then the guess for c(2) was too low. Increase it.
cmin = c(1,j); % Increase lower bound for c(1) to what we chose before
c(1,j) = (cmax+cmin)/2;% New choice for c(1)
break% Exit the for loop and start again.
end
end
dif = abs(max(k(t,j))-kss); % Compute difference between maximum k and kss. If they are close, stop.
end
k(k==0) = max(k(t,j));% The algorithm might stop before we reach period T. In that case, assume we stay at max(k).
end

답변 (1개)

Walter Roberson
Walter Roberson 2021년 3월 1일
you do not reset dif when you move on to the next j value so the while will end immediately.
  댓글 수: 3
Ali Mara
Ali Mara 2021년 3월 1일
for j=1:5
dif=1
tol level
%and then I can put everything else does that make sense ?
end
Walter Roberson
Walter Roberson 2021년 3월 1일
I am not sure what
tol level
is intended to mean. You can initialize tol before the loop as it will be the same for each j.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by