% Fourier_Transform_Alias 
% Author C. Prati
% February 17, 2020
clear
close all

%--------------------------------------------------
% 1
% Let us generate a discrete cosinusoidal signal x with
% frequency sweeping from f=0Hz to f=1000Hz in step of 50Hz
% N=100 samples using a sampling interval T=1/1000 second
% For each frequency, the signal x and its corresponding FFT X
% are plotted

N=100;
T=1/1000;
t=(0:N-1)*T;
tcontinuo=(0:10*N-1)*T/10;

for f=0:50:1000
    
  x=cos(2*pi*f*t);
  xcontinuo=cos(2*pi*f*tcontinuo);
  
  figure(1)
  subplot(211)
  stem(t,x)
  xlabel('time (seconds)')
  hold on
  plot(tcontinuo,xcontinuo,'r')
  hold off
  
  X=fft(x);
  Xshift=fftshift(X);
  
  subplot(212)
  stem((-N/2:N/2-1)/N/T,abs(Xshift),'filled')
  xlabel('frequency (Hz)')
  
  pause
end

  pause
%--------------------------------------------------
% 2
% Let us generate a "continuous" cosinusoidal signal x with
% frequency f1=2Hz spanning a time interval of To=0.99 second.
% The simulation of a continuous time signal is obtained by
% setting a very high sampling frequency compared with the 
% signal frequency. Let us use fs=1000Hz.
fs=1000;
To=0.99;
t=(0:1/fs:To);
f1=2
x=cos(2*pi*f1*t);

%----------------------------------------------------
% 3
% Let us plot the "continuous" signal x in figure 2

figure(2)
plot(t,x)
xlabel('time')
pause

%----------------------------------------------------
% 4
% Let us sample the "continuous" signal x with T=0.05 s.
%(sampling frequency fs=1/T=20Hz)
% Let us plot the obtained samples superimposed to the
% continuous signal x on figure 2.

T=0.05;
nT=(0:T:To);
xn=cos(2*pi*f1*nT);
figure(2)
hold on
stem(nT,xn,'filled','r')
hold off
pause

%----------------------------------------------------
% 5
% Let us compute the number of sample N of the signal xn
% Let us also check this number N by measuring the length of xn

N=floor(To/T)+1
Nmeasured=length(xn)
pause

%----------------------------------------------------
% 6
% Let us compute the FFT X of the sampled signal xn and
% let us plot its absolute value in figure 3

Xn=fft(xn);
Xnshift=fftshift(Xn);

figure(3)
stem((-N/2:N/2-1)/N/T,abs(Xnshift))
xlabel('frequency (Hz)')

%--------------------------------------------------
% 7
% Let us repeat steps from 2 to 4 by increasing the frequency of the
% "continuous" cosinusoidal signal x from f1=2Hz to f2=(2+1/T) Hz

f2=2+1/T
pause
x2=cos(2*pi*f2*t);
figure(4)
plot(t,x2)
xlabel('time')
pause

xn2=cos(2*pi*f2*nT);
figure(4)
hold on
stem(nT,xn2,'filled','r')
hold off
pause

%--------------------------------------------------
% 8
% Let us compare the samples obtained by sampling this two signals 
figure(4)
hold on
plot(t,x,'m')



