%% Filter Signal Using Cascaded Lowpass and Highpass Filters
% *Note*: This example runs only in R2016b or later. If you are using an earlier 
% release, replace each call to the function with the equivalent |step| syntax. 
% For example, |myObject(x)| becomes |step(myObject,x)|.
% 
% Design a bandpass filter by cascading: 
% 
% * A highpass filter with a stopband frequency of 5000 Hz and a passband frequency 
% of 8000 Hz
% * A lowpass filter with a passband frequency of 12,000 Hz and a stopband frequency 
% of 15,000 Hz
% 
% Visualize the frequency response using |fvtool|.

lpFilt = dsp.LowpassFilter('StopbandFrequency',15000,...
    'PassbandFrequency',12000);
hpFilt = dsp.HighpassFilter('StopbandFrequency',5000,...
    'PassbandFrequency',8000);

bpFilt = dsp.FilterCascade(lpFilt,hpFilt);

fvtool(bpFilt);
legend('Bandpass filter');
%% 
% Pass a noisy sine wave as the input to the bandpass filter. The input 
% is a sum of three sine waves with frequencies at 3 kHz, 10 kHz, and 15 kHz. 
% The sampling frequency is 48 kHz. View the input and the filtered output on 
% a spectrum analyzer. 
% 
% The tones at 3 kHz and 15 kHz are attenuated, and the tone at 10 kHz is 
% preserved by the bandpass filter.
%%
Sine1 = dsp.SineWave('Frequency',3e3,'SampleRate',48e3,'SamplesPerFrame',6000);
Sine2 = dsp.SineWave('Frequency',10e3,'SampleRate',48e3,'SamplesPerFrame',6000);
Sine3 = dsp.SineWave('Frequency',15e3,'SampleRate',48e3,'SamplesPerFrame',6000);

SpecAna = dsp.SpectrumAnalyzer('PlotAsTwoSidedSpectrum',false, ...
    'SampleRate',Sine1.SampleRate, ...
    'NumInputPorts',2,...
    'ShowLegend',true, ...
    'YLimits',[-160,60]);

SpecAna.ChannelNames = {'Original noisy signal','Filtered signal'};


for i = 1:1000
    x = Sine1() + Sine2() + Sine3() + 0.1.*randn(Sine1.SamplesPerFrame,1);
    y = bpFilt(x);
    SpecAna(x,y);

end
release(SpecAna)


%% 
% Copyright 2012 The MathWorks, Inc.