%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                           
%       dynport.m: Consumption-savings problem
%
%       The program solves the standard consumption-savings model using the method
%       of undetermined coefficients.
%
%       Carlos Garriga, October 2004
%
%
%    NOTE:
%   1) To evaluate the residual you have to give a guess of the coefficients
%   2) To derive the optimal value funcion call the function with the minimization 
%
%     i.e. [coefficients,residual,conv,options]= fminsearch('dynport',[-2.28,1.8])
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function res=dynport(x)

%clear all;close all; clc; tic; format short
%disp(' ');disp('  CONSUMPTION-SAVINGS PROBLEM (Undetermined coefficients)');disp(' ');

% PARAMETERS
Rate  = 1.0;                             % Exogenous return from savings
beta  = 0.45;                            % Discount rate

% Coefficients for the functional form for the value function v(k)= a0 + a1 log(k)
a0    = x(1);
a1    = x(2);

%----------------------------------------------------------------
% INITIALIZE VARIABLES AND FUNCTIONS
%----------------------------------------------------------------
% Define grid points for cake
wlow  = 0.01;                            % Lowest point in the grid  
whigh = 5;                               % Highest point in the grid
nump  = 25;                              % Number of grid points
ws    = linspace(wlow,whigh,nump)';      % State space
tol   = 1e-5;                            % Tolerance criterium

% Guess for the initial value function and policy function
v1 = zeros(nump,1);                      % Initialize value function
wprime  = zeros(nump,1);                 % Initialize savings policy function
cons    = zeros(nump,1);                 % Initialize consumption policy function


%----------------------------------------------------------------
% COMPUTE VALUE FUNCTION
%----------------------------------------------------------------
% For every point in the grid solve the FOC and compute consumption
%  -U'(Rate*w-w')+beta*V'(w')

    wprime = (a1*beta/(1+a1*beta))*ws*Rate;

    cons = Rate*ws-wprime;

% Compute the value function associated to the optimal policy

    v1 = log(cons) + beta* (a0 + a1*log(wprime));

% Compute the value function associated to the guessed coefficients

    v0  = a0 + a1*log(ws);

%----------------------------------------------------------------
% COMPUTE THE RESIDUAL FUNCTION AND PLOT CONVERGENCE
%----------------------------------------------------------------
% Use different norms

 res = sum((v1-v0).^2);

%res = max(abs(v1-v0));

% Plot convergence of the value function

	plot(ws,v1,'r:',ws,v0); 
	legend('v1','v0')   
	axis([wlow whigh -10 3])
	pause(.1)