%Anton Cheremukhin Econ202b Macro Homework#1 Problem 4
clear;
% parameters from the task
beta=0.6;   alpha=0.3;  A=15;   delta=0.5;
% parameter for computations    used for convergence detection
epsilon = 0.00001;
% optimal steady state value, k*
k_opt = ((1/beta-(1-delta))/(A*alpha))^(1/(alpha-1))
% define main grid as an array of values from 0.05 to 12
K_min = 0.05;
K_max = 12;
K_step = 0.05;
K_grid = [K_min:K_step:K_max];
% interpolation grid
K_finestep = K_step/20;
K_finegrid = [K_min:K_finestep:K_max];
% value function iteration algorithm, computing arrays of V_new for all k from K_grid
V_new = ones(size(K_grid));     V_old = zeros(size(K_grid));
K_pf = zeros(size(K_grid));
while (abs(max(V_new - V_old)) > epsilon)
    V_old = V_new;
    for n = 1 : size(K_grid,2)
        k = K_min + K_step*(n-1);
        % Calculate maximum over all k_primes from our supergrid. 
        [V_new(n),K_pf(n)] = max(log(max(0.000000001*ones(size(K_finegrid)),ones(size(K_finegrid))*(A*(k^alpha)+(1-delta)*k) - K_finegrid)) + beta*interp1(K_grid, V_old, K_finegrid, 'spline'));
    end
end
K_pf = K_finegrid(K_pf);  
figure(1)
plot(K_grid,V_new,...
                'LineWidth',2)
figure(2)
plot(K_grid,K_pf,K_grid,K_grid,...
                'LineWidth',2)