% DFT of a sinusoidal signal:              %emol
% (complex Fourier coefficients)
% (a) data length and frequency resolution %emol
% (b) sampling rate and time resolution    %emol
% (c) display of DFT                       %emol

clc %emol
clearvars %emol
close all %emol

A=2; p=1; Tp=1/p; % amplitude, frequency and period (emol)

% first topic: effect of data length (emol)
T1=1*Tp; T2=2*Tp; % short rectangular window (emol)
% T1=4*Tp; T2=8*Tp; % medium rectangular window (emol)
% --> increase of data length improves frequency resolution, as df=1/T

% second topic: effect of sampling frequency (emol)
fs=10/Tp; %emol
% fs=20/Tp; %emol
% --> increase of sampling frequency does not improve frequency resolution,
%     as fs=1/dt and df=fs/N; but it increases the frequency range to be 
%     computed, as N increases for a fixed T

% third topic: see below (emol)

t1=0:1/fs:T1-1/fs; t2=0:1/fs:T2-1/fs; % distinct time vectors (emol)
x1=A*cos(2*pi*p*t1); x2=A*cos(2*pi*p*t2); % distinct samples (emol)
X1=fft(x1); X2=fft(x2);
N1=length(x1); N2=length(x2);
f1=fs*(0:N1-1)/N1; f2=fs*(0:N2-1)/N2; % distinct frequency vectors (emol)

X1z=fft([x1 zeros(1,5000-N1)]); % zero padding (emol)
X2z=fft([x2 zeros(1,5000-N2)]); % zero padding (emol)
Nz=length(X1z); %emol
fz=fs*(0:Nz-1)/Nz; %emol
% --> it is known that zero padding does not improve 'true' df

figure(1) %emol

subplot(2,2,1)
plot(t1,x1,'ro') %emol
xlabel('Time (s)'); ylabel('Function Value') %emol
axis([0 T1 -A A]) %emol
grid on %emol

subplot(2,2,2) %emol
plot(t2,x2,'ro') %emol
xlabel('Time (s)'); ylabel('Function Value') %emol
axis([0 T2 -A A]) %emol
grid on %emol

subplot(2,2,3) %emol
stem(f1,abs(X1)/fs/T1,'fill');
hold on; %emol
plot(fz,abs(X1z)/fs/T1,'r:'); %emol
hold off %emol
xlabel('Frequency (Hz)'); ylabel('Modulus (scaled)')
axis([0 fs 0 1.2]) %emol
grid on %emol

subplot(2,2,4) %emol
stem(f2,abs(X2)/fs/T2,'fill')
hold on; %emol
plot(fz,abs(X2z)/fs/T2,'r:'); %emol
hold off %emol
xlabel('Frequency (Hz)'); ylabel('Modulus (scaled)')
axis([0 fs 0 1.2]) %emol
grid on %emol

% % third topic: centered display of discrete Fourier transform
% % --> positive and negative frequencies are displayed via use of fftshift
% 
% figure(2) %emol
% 
% subplot(2,1,1) %emol
% f1c=fs/N1*(-floor(N1/2):floor((N1-1)/2)); %emol
% fzc=fs/Nz*(-floor(Nz/2):floor((Nz-1)/2)); %emol
% stem(f1c,fftshift(abs(X1)/fs/T1),'fill'); %emol
% hold on; %emol
% plot(fzc,fftshift(abs(X1z)/fs/T1),'r:'); %emol
% hold off %emol
% xlabel('Frequency (Hz)'); ylabel('Modulus (scaled)') 
% axis([-fs/2 fs/2 0 1.2]) %emol
% grid on %emol
% 
% subplot(2,1,2) %emol
% f2c=fs/N2*(-floor(N2/2):floor((N2-1)/2)); %emol
% stem(f2c,fftshift(abs(X2)/fs/T2),'fill') %emol
% hold on; %emol
% plot(fzc,fftshift(abs(X2z)/fs/T2),'r:'); %emol
% hold off %emol
% xlabel('Frequency (Hz)'); ylabel('Modulus (scaled)')
% axis([-fs/2 fs/2 0 1.2]) %emol
% grid on %emol