%--------------------------------------------------------------------------
%     *** 2.161 Signal Processing - Continuous and Discrete  ***
%                      Tutorial MATLAB Function
%
% LSadapt - Demonstration adaptive FIR filter design and implementation
%
% Source:   Class Handout: Introduction to Least-Squares Adaptive Filters  
%
% Usage :   1) Initialization:
%            y = LSadapt('initial', Lambda, FIR_N)
%             where Lambda is the convergence rate parameter.
%                   FIR_N is the filter length. 
%             Example:
%                  [y, e] = adaptfir('initial', .01, 51);
%             Note: LSadapt returns y = 0 for initialization
%           2) Filtering:
%            [y, b] = adaptfir(f, d};
%             where f is a single input value,
%                   d is the desired value, and
%                   y is the computed output value,
%                   b is the coefficient vector.
%
% Version:  1.0
% Author:   D. Rowell   12/9/07
% -------------------------------------------------------------------------
% 
function [y, bout] = LSadapt(f, d ,FIR_M)
persistent f_history b lambda M
%
% The following is initialization, and is executed once
%
if (ischar(f) && strcmp(f,'initial'))
    lambda = d;
    M = FIR_M;
    f_history = zeros(1,M);
    b = zeros(1,M);
    b(1) = 1;
    y = 0;
    else
% Filtering: 
    for J=M:-1:2
        f_history(J) = f_history(J-1);
    end;
    f_history(1) = f;
    % Perform the convolution
    y = 0;
    for J = 1:M
        y = y + b(J)*f_history(J);
    end;
    % Copmpute the error and update the filter coefficients for the next iteration
    e = d - y;
    for J = 1:M
        b(J) = b(J) + lambda*e*f_history(J);
    end;
    bout=b;
end
