clear all

% parameters (notation as in class notes)
xi = .15;
sig2_u = 1;
sig2_v = 6;

% supplementary parameters: T is the length of impulse response at the end
% iter is number of iterations, crit is convergence criterion
T= 12;
iter = 1000;
crit = 1e-12;

% initial guess for phi
phi = 1;

% this loop solves for phi
for j=1:iter
    
A = [1 0; phi 1-phi];
F = [1 0];
Sig1 = sig2_u*[1 phi]'*[1 phi];
Sig2 = sig2_v;
P = eye(2);

% next loop solves Kalman filter
for i = 1:iter
    K = P*F'/(F*P*F'+Sig2);
    Phat = P - K*F*P;
    Pi = A*Phat*A'+Sig1;
    dist = sum(sum(Pi-P).^2)/9;
    P = Pi;
    if dist<crit
        break
    end
end
if i==iter && dist>crit
    display('conv not achieved in loop 1')
end

% update phi and check convergence
phi_i = [xi 1-xi]*K;
dist = (phi_i-phi)^2;
if dist<crit
    break
end
phi = phi_i;
end

if i==iter && dist>crit
    display('conv not achieved in loop 2')
end

% compute impulse responses to shock u_t
x(:,1) = [1 phi]';
for t = 1:T
    x(:,t+1) = A*x(:,t);
end

% plot response of prices
plot(x(2,:))
hold on
