%-------------------------------------------------------------------------
%     *** 2.161 Signal Processing - Continuous and Discrete  ***
%                      Tutorial MATLAB Function
%
% iirdf2 - Demonstration IIR Direct Form II filter implementation.
% 
% Source:   Class handout:  Direct Form Digital Filter Structures
%
% Usage :   1) Initialization:
%              y = iirdf2('initial', b, a)
%                where b, a are the numerator and denominator polynomial 
%                coefficients.  Example:
%                   [b,a] = butter(7,0.4);
%                   y = iirdf2('initial',b,a);
%                Note: iirdf2 returns y = 0 for initialization
%           2) Filtering:
%              y_out = iirdf2(f_{in};
%                where f_in 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) = iirdf2(1);
%                   end
%
% See also: iirdf1
%
% Version:  1.0
% Author:   D. Rowell   11/18/07
% -------------------------------------------------------------------------
% 
function y_n = iirdf2(f_n,B,A)
persistent register Bx Ax N
%
% The following is initialization, and is executed once
%
if (ischar(f_n) && strcmp(f_n,'initial'))
    N = length(A);
    Ax = A;
    Bx = B;
    register = zeros(1,N);
    y_n = 0;
    else
% Filtering:   (Note that a Direct Form II filter needs only a single
% shift register.)
    x = 0; y = 0;
    for J = N:-1:2
        register(J) = register(J-1);        % Move along the shift register
        x = x - Ax(J)*register(J);
        y = y + Bx(J)*register(J);
    end
    x   = x + f_n;
    y_n = y + Bx(1)*x;
    register(1) = x;
end
