%% This code is a modified version of code written
%% on 10-08-2021 by Prof. Brian L. Evans during
%% office hours.
%% It's a way to validate your manual calculations
%% on homework 4.4(b) and homework 5.3(b).
%% Keep in mind that the first element in a vector
%% in MATLAB has index 1 and not 0.

%% USAGE
%% FIR filters convolve the input signal and the
%% FIR filter impulse response (which is equal to
%% the filter coefficients). When the input signal
%% is finite in length, the output is finite length:
%%
%% Length of y = length of x + Number of Coeffs - 1
%%
%% Giving finite-length signals x and y, we can
%% determine how many filter coefficients there are.
%%
%% If the input signal is infinite in length, then
%% the output could be either infinite or finite
%% in length.

%% Define the input and output signals
%% Given an equal number of x and y values if
%% x is to be considered infinite length.

x = [ 1 2 3 4 5 ];
y = [ 1 1 1 1 1 -5 ];

%% Determine Nmax based on input signal
%%   Finite-length   length(y) - length(x) + 1
%%   Infinite-length length(x)
Nmax = length(y) - length(x) + 1;   %% finite-length input signal
if ( Nmax < 2 )
    Nmax = length(x);
end

b = zeros(1, Nmax);
b(1) = y(1) / x(1);
% b(2) = ( y(2) - b(1)*x(2) ) / x(1);
% b(3) = ( y(3) - b(1)*x(3) - b(2)*x(2) ) / x(1);
for k = 2:Nmax
    numer = y(k);
    n = k;
    for m = 1:(k-1)
	if (n >= 1)
            numer = numer - b(m) * x(n);
	end
        n = n - 1;
    end
    b(k) = numer / x(1);
end
