%-----------------------------------------------------------------
%     *** 2.161 Signal Processing - Continuous and Discrete  ***
%                      Tutorial MATLAB Function
%
% LSQFilt - Demonstration routine for Least-Squares FIR filter design
%
% Source:   Class handout:  MATLAB Examples of Least-Squares Filter
%           Design
%
% Usage :   [B,MSE] = LSQFilt(f,d,M)
%               f - row vector of data samples    - length N
%               d - row vector of desired values - length N
%               M - filter order
% Returns:  B -   vector of optimal filter coefficients
%           MSE - minimized value of the mean-square-error
%
% Note: This routine is for tutorial purposes only. The Levinson method for
%       Toeplitz matrix inversion would be used in practical methods.
%
% Author:  D. Rowell
% Revised: 10/29/07
%-----------------------------------------------------------------
%
function [B,MSE] = LSQFilt(f,d,M)

     N = length(f);
% Compute the correlation coefficients.
% Note that matlab defines the cross-correlaton backwards!! and 
% we need to reverse the order of the subscripts.
%
     phiff=xcorr(f);
     phifd=xcorr(d,f);
%
% Extract out the central regions (low-lag values) and form
% the autocorrelation matrix.
%
     rff=phiff(N:N+M-1);
     R = toeplitz(rff);
     P=phifd(N:N+M-1);
%
% Compute the optimal filter coefficients
%
     B=inv(R)*P';
%
% and the residual mean-square-error
%
     phidd=xcorr(d);
     MSE=phidd(N) - P*B;
%
%------------------------------------------------------------------------


