%% Spectral Estimation Using Filter Bank
% Compare spectral estimates of sinusoids embedded in white Gaussian noise using 
% a Hann window-based Welch method and filter bank method.
%% Initialization
% Initialize two |dsp.SpectrumEstimator| objects. Specify one estimator to use 
% the Welch-based spectral estimation technique with a Hann window. Specify the 
% other estimator to use an analysis filter bank to perform the spectral estimation. 
% Specify a noisy sine wave input signal with 4 sinusoids at 0.16, 0.2, 0.205, 
% and 0.25 cycles/sample. View the spectral estimate using an array plot.

FrameSize = 420;
Fs = 1;
sinegen = dsp.SineWave('SampleRate',Fs,...
    'SamplesPerFrame',FrameSize,...
    'Frequency',[0.16 0.2 0.205 0.25],...
    'Amplitude',[2e-5 1  0.05  0.5]);
NoiseVar = 1e-10;
numAvgs = 8;

hannEstimator = dsp.SpectrumEstimator('PowerUnits','dBm',...
    'Window','Hann','FrequencyRange','onesided',...
    'SpectralAverages',numAvgs,'SampleRate',Fs);

filterBankEstimator = dsp.SpectrumEstimator('PowerUnits','dBm',...
    'Method','Filter bank','FrequencyRange','onesided',...
    'SpectralAverages',numAvgs,'SampleRate',Fs);

spectrumPlotter = dsp.ArrayPlot(...
    'PlotType','Line','SampleIncrement',Fs/FrameSize,...
    'YLimits',[-250,50],'YLabel','dBm',...
    'ShowLegend',true,'ChannelNames',{'Hann window','Filter bank'});
%% Streaming
% Stream the input. Compare the spectral estimates computed using the Hann window 
% and the analysis filter bank
%%
for i = 1:1000
    x = sum(sinegen(),2) + sqrt(NoiseVar)*randn(FrameSize,1);
    Pse_hann = hannEstimator(x);
    Pfb = filterBankEstimator(x);
    spectrumPlotter([Pse_hann,Pfb])
end

%%
% 
% The Hann window misses the peak at 0.205 cycles/sample. In addition, the 
% window has a significant spectral leakage that makes the peak at 0.16 cycles/sample 
% hard to distinguish, and the noise floor is not correct. 
% 
% The filter bank estimate has a very good resolution with no spectral leakage.

%% 
% Copyright 2012 The MathWorks, Inc.