I need help with running two for loops

4 visualizaciones (últimos 30 días)
Ali Mara
Ali Mara el 1 de Mzo. de 2021
Comentada: Walter Roberson el 1 de Mzo. de 2021
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

Respuestas (1)

Walter Roberson
Walter Roberson el 1 de Mzo. de 2021
you do not reset dif when you move on to the next j value so the while will end immediately.
  3 comentarios
Ali Mara
Ali Mara el 1 de Mzo. de 2021
for j=1:5
dif=1
tol level
%and then I can put everything else does that make sense ?
end
Walter Roberson
Walter Roberson el 1 de Mzo. de 2021
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.

Iniciar sesión para comentar.

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by