function [s,M] = hpfilter(y,lambda)
%
%  Author: Ivailo Izvorski, 
%          Department of Economics
%          Yale University.
%          izvorski@econ.yale.edu
%
%  function [s]=hpfilter(y,lambda)
%
%  Hodrick Prescott filter where:
%  lambda - smoothing parameter; w = 1600 for quarterly data
%  y      - the original input series that has to be smoothed
%  s      - the filtered series, the HP-trend
%  M      - the matrix used to filter the input series to get the HP-trend
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if size(y,1) < size(y,2);
   y = y';
end;

t = size(y,1);
a = 6*lambda+1;
b = -4*lambda;
c = lambda;
d = [c,b,a];
d = ones(t,1)*d;
m = diag(d(:,3)) + diag(d(1:t-1,2),1) + diag(d(1:t-1,2),-1);
m = m + diag(d(1:t-2,1),2) + diag(d(1:t-2,1),-2);

m(1,1)     = 1+lambda;       m(1,2)   = -2*lambda;
m(2,1)     = -2*lambda;      m(2,2)   = 5*lambda+1;
m(t-1,t-1) = 5*lambda+1;     m(t-1,t) = -2*lambda;
m(t,t-1)   = -2*lambda;      m(t,t)   = 1+lambda;

s = inv(m) * y;

M = inv(m);
%save c:\user\matlab\solve\ch3\hpfil.mat M;

