%HP   Hodrick-Prescott filter
%   C = HP(Y,LAM) for T-by-N vector Y (data) and positive scalar LAM 
%   (smoothing parameter) computes detrended series using HP filter.
%
%   [C,X] = HP(Y,LAM) computes detrended series C and trend component X.
%
function [c,x] = hp(y,lam)

t = size(y,1);
G = eye(t)*(1+6*lam);
C1 = [1+lam;-2*lam;lam;zeros(t-3,1)];
C2 = [-2*lam;1+5*lam;-4*lam;lam;zeros(t-4,1)];
CTm1 = [zeros(t-4,1);lam;-4*lam;1+5*lam;-2*lam];
CT = [zeros(t-3,1);lam;-2*lam;1+lam];
G = [C1 C2 G(:,3:(t-2)) CTm1 CT];
k = find(G == 1+6*lam);
G(k-2) = lam;
G(k-1) = -4*lam;
G(k+1) = -4*lam;
G(k+2) = lam;
x = G\y;
c = y - x;
%
%                                               G. Ramey - UCSD - 4/9/05