%spectral leakage demonstration
clear all
close all
N = 128;

%assign normalized frequency range, f = k/N
%where f=1 is sampling rate

df=1/N;
%df=1/1024;
df=1/2048;
f=0:df:1/16;

figure(1)
y = ones(N,1);

for k=1:length(f)
s(k)=0;
for l=1:N
s(k) = s(k) + (y(l)*exp(1i*2*pi*(l-1)*f(k)));
end
end

spec=abs(s);
subplot(2,1,1)
plot(1:N,y)
title('Rectangular Window; N=128')
axis([0 N-1 0 1.5]);
subplot(2,1,2)
plot(f,20*log10(spec/N));
xlabel('f/r')
ylabel('dB')
xlim([0 1/16]);
ylim([-80 0])

disp('The rectangle window is the mathematical default if you choose no window')
pause
figure(2)

y = bartlett(N);
for k=1:length(f)
s(k)=0;
for l=1:N
s(k) = s(k) + (y(l)*exp(1i*2*pi*(l-1)*f(k)));
end
end

spec=abs(s);
subplot(2,1,1)
plot(1:N,y)
xlabel('n')
title('Bartlett Window; N=128')
axis([0 N-1 0 1.5]);
subplot(2,1,2)
plot(f,20*log10(spec/sum(y)));
xlabel('f/r')
ylabel('dB')
xlim([0 1/16]);
ylim([-80 0])

disp('A triangle window is also known as a Bartlett window')
pause
figure(3)

y = kaiser(N,4);
for k=1:length(f)
s(k)=0;
for l=1:N
s(k) = s(k) + (y(l)*exp(1i*2*pi*(l-1)*f(k)));
end
end
spec=abs(s);
subplot(2,1,1)
plot(1:N,y)
xlabel('n')
title('Kaiser Window; N=128')
axis([0 N-1 0 1.5]);
subplot(2,1,2)
plot(f,20*log10(spec/sum(y)));
xlim([0 1/16]);
ylim([-80 0])
xlabel('f/r')
ylabel('dB')

disp('The Kaiser window is constructed from bessel functions.')
pause
figure(4)

y = hamming(N);
for k=1:length(f)
s(k)=0;
for l=1:N
s(k) = s(k) + (y(l)*exp(1i*2*pi*(l-1)*f(k)));
end
end
spec=abs(s);
subplot(2,1,1)
plot(1:N,y)
xlabel('n')
title('Hamming Window; N=128')
axis([0 N-1 0 1.5]);
subplot(2,1,2)
plot(f,20*log10(spec/sum(y)));
xlim([0 1/16]);
ylim([-80 0])
xlabel('f/r')
ylabel('dB')

disp('The Hamming window is a cosine taper')
pause
figure(5)

y = hanning(N);
for k=1:length(f)
s(k)=0;
for l=1:N
s(k) = s(k) + (y(l)*exp(1i*2*pi*(l-1)*f(k)));
end
end
spec=abs(s);
subplot(2,1,1)
plot(1:N,y)
xlabel('n')
title('Hanning Window; N=128')
axis([0 N-1 0 1.5]);
subplot(2,1,2)
plot(f,20*log10(spec/sum(y)));
xlim([0 1/16]);
ylim([-80 0])
xlabel('f/r')
ylabel('dB')

disp('The Hanning window is also a cosine taper but includes the zero weight points at the edges')
