% Tuneup #7 for mini project #2
% Filter bank using two-sample average and first-order difference
% filter coefficients
LA = [0.5, 0.5]; % Lowpass Analysis
HA = [0.5, -0.5]; % Highpass Analysis
LS = [1, 1]; % Lowpass Synthesis
HS = [-1, 1]; % Highpass Synthesis
%% Part (a):
% Use freqz to plot the frequency response of the averaging fitler (LA)
% and the difference filter (H)
%% Part (b): analyzing one level transform
% The code below shows the spectrogram for the high-pass and low-pass
% branches during each part of the filter bank. Describe the the effect
% that each each step has on the chirp signal.
% Input: chirp signal
fs = 1000;
t = linspace(0,5,5*fs);
f0 = 0;
fstep = 100;
x = cos(2*pi*f0*t + pi*fstep*t.*t);
figure; spectrogram(x,64,0,64,fs,'yaxis'); caxis([-25,-15]);
title('chirp signal');
% Low-pass analyis filter
xL0 = conv(x,LA);
figure; tiledlayout(1,2); nexttile;
spectrogram(xL0,64,0,64,fs,'yaxis'); caxis([-25,-15]);
title('After two sample averaging filter');
% High-pass analysis filter
xH0 = conv(x,HA);
nexttile; spectrogram(xH0,64,0,64,fs,'yaxis'); caxis([-25,-15]);
title('After first order difference filter');
% Downsample
xL1 = downsample(xL0,2);
figure; tiledlayout(1,2); nexttile;
spectrogram(xL1,64,0,64,fs/2,'yaxis'); caxis([-25,-15]);
title('Low frequency component after downsampling');
xH1 = downsample(xH0,2);
nexttile; spectrogram(xH1,64,0,64,fs/2,'yaxis'); caxis([-25,-15]);
title('High frequency component after downsampling');
% Upsample
xL2 = upsample(xL1,2);
figure; tiledlayout(1,2); nexttile;
spectrogram(xL2,64,0,64,fs/2,'yaxis'); caxis([-25,-15]);
title('Low frequency component after downsampling and upsampling');
xH2 = upsample(xH1,2);
nexttile; spectrogram(xH2,64,0,64,fs/2,'yaxis'); caxis([-25,-15]);
title('High frequency component after downsampling and upsampling');
% Low-pass synthesis filter
xL3 = conv(xL2,LS);
figure; tiledlayout(1,2); nexttile;
spectrogram(xL3,64,0,64,fs,'yaxis'); caxis([-25,-15]);
title('Output of low pass branch');
% High-pass synthesis filter
xH3 = conv(xH2,HS);
nexttile; spectrogram(xH3,64,0,64,fs,'yaxis'); caxis([-25,-15]);
title('Output of high pass branch');
%% Part (c) frequency response for two-level transform
% the code below plots the effective frequency response corresponding to:
% Lowpass -> downsample -> Lowpass -> downsample
% Modify the code to instead plot the effective response corresponding to:
% Lowpass -> downsample -> Highpass -> downsample
Nplot = 101;
[HLA, w] = freqz(LA,1,Nplot);
[HLS, w] = freqz(LS,1,Nplot);
HLA2 = downsample([HLA; flipud(conj(HLA))],2);
HLS2 = downsample([HLS; flipud(conj(HLS))],2);
figure;
low_low = 0.25*HLA.*HLA2.*HLS2.*HLS;
hold on; plot(w,abs(low_low), linewidth=3)
xlim([0,pi]);
set(gca,'XTick',[0,pi/4,pi/2,pi])
set(gca,'XTickLabels',["0", "\pi/4","\pi/2","\pi"])
xlabel('Frequency \omega [radians per sample]')
ylabel('Magnitude response | H(e^{j\omega}) |')