%-----------------------------------------------------------------
%     *** 2.161 Signal Processing - Continuous and Discrete  ***
%                      Tutorial MATLAB Function
%
% firdf -   Demonstration FIR direct form implementation
%
% Source:   Class handout:  Direct Form Digital Filter Structures
%
% Usage :   1) Initialization:
%             y = firdf('initial', b)
%               where b are the numerator polynomial coefficients. 
%                Example: y = iirdf1('initial',[1 2 5 2 1]);
%                Note: firdf returns y = 0 for initialization
%           2) Filtering:
%             y_out = firdf(f);
%             where f is a single input value, and
%                   y_out is the computed output value.
%               Example: To compute the step response:
%                     for j=1:100
%                        y(j) = firdf(1);
%                     end
%
% Version:  1.0
% Author:   D. Rowell   11/20/07
% -------------------------------------------------------------------------
%
function y_n = firdf(f_n,B)
persistent f_register Bx N
%
% The following is initialization, and is executed once
%
if (ischar(f_n) && strcmp(f_n,'initial'))
    N = length(B);
    Bx = B;
    f_register = zeros(1,N);
    y_n = 0;
    else
% Filtering:
    y_n = 0;
    for J = N:-1:2
        f_register(J) = f_register(J-1);
        y_n = y_n + Bx(J)*f_register(J);
    end
    y_n = y_n + Bx(1)*f_n;
    f_register(1) = f_n;
end
