%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  Code for DSP Lecture of Dec. 29, 2007
%
%  Different parts are separated by "pause"
%   You need to press a key to proceed
%   to following part
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%% Study of Windowing
%% Available Windows in Matlab
figure(1);
N= 32;
w0= window(@rectwin,N);
w1= window(@bartlett,N);
w2= window(@hamming,N);
w3= window(@hann,N);
w4= window(@blackman,N);
w5= window(@gausswin,N);

n= 1:N;
plot(n,w0,'k', n,w1,'b', n,w2,'g', n, w3, 'r',n,w4,'m',n,w5,'c');
axis([1 N 0 1.1]);
legend('Boxcar','Bartlett','Hamming', 'Hanning','Blackman','Gaussian');
xlabel('Sample (n)');
ylabel('Amplitude');
title('Comparison of Windowing Functions in the Time Domain');


%%%%%% Now let's look at their Fourier transforms
M= 1024;
fw0= fftshift(fft(w0,M));
fw1= fftshift(fft(w1,M));
fw2= fftshift(fft(w2,M));
fw3= fftshift(fft(w3,M));
fw4= fftshift(fft(w4,M));
fw5= fftshift(fft(w5,M));
figure(2);
n= 1:M;
plot(n,abs(fw0),'k', n,abs(fw1),'b', n,abs(fw2),'g', n,abs(fw3),'r',n,abs(fw4),'m',n,abs(fw5),'c');
legend('Boxcar','Bartlett','Hamming', 'Hanning','Blackman','Gaussian');
xlabel('Frequency (k)');
ylabel('Magnitude (abs scale)');
title('Comparison of Windowing Functions in the Frequency Domain');
figure(3);
semilogy(n,abs(fw0),'k', n,abs(fw1),'b', n,abs(fw2),'g', n,abs(fw3),'r',n,abs(fw4),'m',n,abs(fw5),'c');
legend('Boxcar','Bartlett','Hamming', 'Hanning','Blackman','Gaussian');
xlabel('Frequency (k)');
ylabel('Magnitude (log scale)');
title('Comparison of Windowing Functions in the Frequency Domain');

%%%%%% Effect of Windowing on Spectral Analysis of Sinusoidal Signals
T= 1e-4;            % Sampling rate of 10k
n= (1:64)*T;        % Sampling points
A0= 1;
A1= 0.75;
s1= A0*cos(2*pi/6.*1e4*n)+A1*cos(2*pi/3.*1e4*n);
s2= A0*cos(2*pi/14.*1e4*n)+A1*cos(4*pi/15.*1e4*n);
s3= A0*cos(2*pi/14.*1e4*n)+A1*cos(2*pi/12.*1e4*n);
s4= A0*cos(2*pi/12.*1.0001e4*n)+A1*cos(4*pi/25.*1e4*n);
win1= window(@blackman,64);
win2= window(@rectwin,64);
win3= window(@hamming,64);
win4= window(@hanning,64);
s1=s2.*win1';
s2=s2.*win2';
s3=s2.*win3';
s4=s2.*win4';

fs1= fftshift(fft(s1,M));
fs2= fftshift(fft(s2,M));
fs3= fftshift(fft(s3,M));
fs4= fftshift(fft(s4,M));
k=((1:M)*1./M-0.5)*2*pi;
figure(4);
subplot(2,2,1); plot(k,abs(fs1)); title('Fig. 13(b)'); xlabel('Frequency'); ylabel('Magnitude');
subplot(2,2,2); plot(k,abs(fs2)); title('Fig. 13(c)'); xlabel('Frequency'); ylabel('Magnitude');
subplot(2,2,3); plot(k,abs(fs3)); title('Fig. 13(d)'); xlabel('Frequency'); ylabel('Magnitude');
subplot(2,2,4); plot(k,abs(fs4)); title('Fig. 13(e)'); xlabel('Frequency'); ylabel('Magnitude');














