function yd=trend(y,phi)
%TREND detrends series y using the Hodrick-Prescott method of detrending
%
%  INPUTS:
%    (i) y = vector of length n, series to be detrended
%   (ii) phi = parameter used in detrending; the smaller is phi, the 
%              smoother is the trend path (e.g. if phi=0, the least 
%              squares linear trend results).  To detrend quarterly
%              data, Hodrick and Prescott use phi=1600.
%
%  OUTPUT: yd, the detrended series
%
%  NOTES: for details, see:  Prescott, ``Theory Ahead of Business Cycle 
%         Measurement,'' QUARTERLY REVIEW, Federal Reserve Bank of 
%         Minneapolis, Fall 1986.
%       
y=y(:);
lts=length(y);
TI=[1+phi   -2*phi   phi                       zeros(1,lts-3);
    -2*phi  1+5*phi  -4*phi  phi               zeros(1,lts-4);
                  zeros(lts-4,lts);
    zeros(1,lts-4)        phi  -4*phi  1+5*phi -2*phi;     
    zeros(1,lts-3)               phi   -2*phi   1+phi];
for i=3:lts-2;
  TI(i,i-2)=phi;
  TI(i,i-1)=-4*phi;
  TI(i,i)=1+6*phi;
  TI(i,i+1)=-4*phi;
  TI(i,i+2)=phi;
end;
yd=TI\y;
