%% Compare Multistage Decimator Designs
% Design a decimator with an overall decimation factor of 24 using the designMultistageDecimator function. Design the filter in two configurations:
% Two-stage configuration - NumStages is set to 2.
% Auto configuration - NumStages is set to 'Auto'. This configuration designs a filter with the lowest number of multiplications per input sample.
% Compare the cost of implementing both the configurations.
%
%% Initialization
% Choose a decimation factor of 24, input sample rate of 6 kHz, stopband attenuation of 90 dB, and a transition width of 0\ldotp 03\times \frac{6000}{2}.

M = 24;
Fs = 6000;
Astop = 90;
TW = 0.03*Fs/2;

%
%% Design the Filter
% Design the two filters using the designMultistageDecimator function.

cAuto = designMultistageDecimator(M,Fs,TW,Astop,'NumStages','Auto')
cTwo = designMultistageDecimator(M,Fs,TW,Astop,'NumStages',2)

% View the filter information using the info function. The 'Auto' configuration designs a cascade of three FIR decimators with decimation factors 2, 3, and 4, respectively. The two-stage configuration designs a cascade of two FIR decimators with decimation factors 4 and 6, respectively.
%
%% Compare the Cost
% Compare the cost of implementing the two designs using the cost function.

cost(cAuto)
cost(cTwo)

% The 'Auto' configuration decimation filter yields a three-stage design that out-performs the two-stage design on all cost metrics.
%
%% Compare the Magnitude Response
% Comparing the magnitude response of the two filters, both the filters have the same transition-band behavior and follow the design specifications.

fvtool(cAuto,cTwo,'magnitude')
legend('Auto multistage','Two-stage')

% However, to understand where the computational savings are coming from in the three-stage design, look at the magnitude response of the three stages individually.

autoSt1 = cAuto.Stage1;
autoSt2 = cAuto.Stage2;
autoSt3 = cAuto.Stage3;
fvtool(autoSt1, autoSt2, autoSt3,'magnitude')
legend('Stage 1','Stage 2','Stage 3')

% The third stage provides the narrow transition width required for the overall design (0.03\timesFs/2). However, the third stage operates at 1.5 kHz and has spectral replicas centered at that frequency and its harmonics.
% The first stage removes such replicas. This first and second stages operate at a faster rate but can afford a wide transition width. The result is a decimate-by-2 first-stage filter with only 7 nonzero coefficients and a decimate-by-3 second-stage filter with only 19 nonzero coefficients. The third stage requires 47 coefficients. Overall, there are 73 nonzero coefficients for the three-stage design and 100 nonzero coefficients for the two-stage design.
% Copyright 2018 The MathWorks, Inc.