%  This script shows the effects of sampling (aliasing) by
%  ploting 3 sinwaves, 2 of which will be aliased.  Matlab
%  programs effectively sample the signal through points define
%  on the time axes use to evaluate the continuous functions on.
%  So one time axis "t" will be created with a rate that modles
%  the physical sampling process (i.e. through the A-to-D device).
%  Another time axis "th" will be sampled at a super rate (so
%  that no aliasing occurs for any of the example signals) for
%  the sake of plotting and comparing the non-alised versions
%  of the signal.  The script generate 6 plots in figure windows
%  1 through 6
%


fs = 100;  %  Set Sampling rate in Hz
dur = .2;   %  Duration for plotting signals in seconds
f0 = 30;   %  Frequency of sinusoid 1 in Hz
f1 = 80;   %  Frequency of sinusoid 2 in Hz
f2 = 210;  %  Frequency of sinusoid 3 in Hz
t = [0:round(dur*fs)]/fs;   %  Create time samples
%  Create and plot signal 1
s0 = cos(2*pi*f0*t); figure(1); plot(t,s0); xlabel('Seconds');
title([num2str(f0) 'Hz signal, sampled at ' num2str(fs)])
%  Create and plot signal 2
s1 = cos(2*pi*f1*t); figure(2); plot(t,s1); xlabel('Seconds');
title([num2str(f1) 'Hz signal, sampled at ' num2str(fs)])
%  Create and plot signal 3
s2 = cos(2*pi*f2*t); figure(3); plot(t,s2); xlabel('Seconds');
title([num2str(f2) 'Hz signal, sampled at ' num2str(fs)])

%  Increase sampling rate to eliminate aliasing and compare aliased 
%  and nonaliased signal in a plot
fsh = 10000;  %  Sampling rate in Hz
th = [0:round(dur*fsh)]/fsh;   %  Create time samples
%  Create and plot signal 1 at higher sampling rate
sh = cos(2*pi*f0*th); figure(4); plot(th,sh); xlabel('Seconds');
%  Overlay first sampled version on top
hold on
stem(t,s0, 'r','Linewidth',2)
title([num2str(f0) 'Hz signal, sampled at ' num2str(fsh) 'Hz and ' num2str(fs) 'Hz (stem)' ])
hold off
%  Create and plot signal 2 at higher sampling rate
sh = cos(2*pi*f1*th); figure(5); plot(th,sh); xlabel('Seconds');
%  Overlay first sampled version on top
hold on
stem(t,s1, 'r','Linewidth',2)
title([num2str(f1) 'Hz signal, sampled at ' num2str(fsh) 'Hz and ' num2str(fs) 'Hz (stem)' ])
hold off
%  Create and plot signal 3 at higher sampling rate
sh = cos(2*pi*f2*th); figure(6); plot(th,sh); xlabel('Seconds');
%  Overlay first sampled version on top
hold on
stem(t,s2, 'r','Linewidth',2)
title([num2str(f2) 'Hz signal, sampled at ' num2str(fsh) 'Hz and ' num2str(fs) 'Hz (stem)' ])
hold off