%% Configure an FIR Filter for Integer Filtering
% Two parts comprise this example. Part 1 compares the step response of an FIR filter in both the fractional and integer filter modes. Fractional mode filtering is essentially the opposite of integer mode. Integer mode uses a filter which has coefficients represented by integers. Fractional mode filters have coefficients represented in fractional form (nonzero fraction length).
% The second part of the example depends on the following - after you filter a set of data, the input data and output data cover the same range of values, unless the filter process introduces gain in the output. Converting your filter object to integer form, and then filtering a set of data, does introduce gain into the system. When the examples refer to resetting the output to the same range as the input, the examples are accounting for this added gain feature.

b = rcosdesign(.25,4,25,'sqrt');
hd = dfilt.dffir(b);
hd.Arithmetic = 'fixed';
hd.InputFracLength = 0; % Integer inputs.
x = ones(100,1);
yfrac = filter(hd,x); % Fractional mode output.
g = set2int(hd);      % Convert to integer coefficients.
yint = filter(hd,x);  % Integer mode output.

%
% Note that yint and yfrac are fi objects. Later in this example, use the fi object properties WordLength and  FractionLength to work with the output data. Now use the gain g to rescale the output from the integer mode filter operation. Verify that the scaled integer output is equal to the fractional output.

yints = double(yint)/g;

%
% Verify that the scaled integer output is equal to the fractional output.

max(abs(yints-double(yfrac)))

%
% In part two, the example reinterprets the output binary data, putting the input and the output on the same scale by weighting the most significant bits in the input and output data equally.

WL = yint.WordLength;
FL = yint.FractionLength + log2(g);
yints2 = fi(zeros(size(yint)),true,WL,FL);
yints2.bin = yint.bin;
max(abs(double(yints2)-double(yfrac)))

% Copyright 2012 The MathWorks, Inc.