echo off
%  E_12_1
%
%  Examples of aliasing in time and frequency domains
clc
clf

% Four time bases, at four sampling rates.
t1 = 0:.001:10;
t2 = 0:.01:10;
t3 = 0:.05:10;
t4 = 0:.1:10;

% Four samples of a cosine at 60 rad/sec
s1 = cos(60*t1);
s2 = cos(60*t2);
s3 = cos(60*t3);
s4 = cos(60*t4);

% Plots of the four samples
subplot(221)
plot(t1,s1)
axis([0 1 -1 1])
title('.001 s sampling rate')
subplot(222)
plot(t2,s2)
axis([0 1 -1 1])
title('.01 s sampling rate')
subplot(223)
plot(t3,s3)
axis([0 1 -1 1])
title('.05 s sampling rate')
subplot(224)
plot(t4,s4)
axis([0 1 -1 1])
title('.1 s sampling rate')
clc
fprintf('Results show the effect of different sampling frequencies\n')
fprintf('and aliasing.\n\nPress any key to continue.\n\n\n\n')
pause

subplot(111)
plot(t1,s1,'w',t2,s2,'go')
axis([0 1 -1 1])
fprintf('Differences between the first and second sampling rates.\n\n')
pause

plot(t1,s1,'w',t3,s3,'go')
axis([0 1 -1 1])
fprintf('Differences between the first and third sampling rates.\n\n')
pause

plot(t1,s1,'w',t4,s4,'go')
axis([0 1 -1 1])
fprintf('Differences between the first and fourth sampling rates.\n\n')
pause

clf
clc

S1 = fftshift(abs(fft(s1,1024)));
S2 = fftshift(abs(fft(s2,1024)));
S3 = fftshift(abs(fft(s3,1024)));
S4 = fftshift(abs(fft(s4,1024)));

w1 = -500:1000/1024:500-1/1024;
plot(w1,S1);

fprintf('Frequency spectrum: First sampling rate.\n')
fprintf('Peak is at 60 rad/sec.\n\n')

fprintf('Press any key to continue.\n\n')
pause

w2 = -50:100/1024:50-1/1024;
plot(w2,S2);
fprintf('Frequency spectrum: Sampling rate halved.\n')
fprintf('Peak is still at 60 rad/sec.\n\n')
fprintf('Press any key to continue.\n\n')
pause

w3 = -25:50/1024:25-1/1024;
plot(w3,S3);
fprintf('Frequency spectrum: Sampling rate again halved.\n')
fprintf('Peak is still at 60 rad/sec, but it''s close to the edge.\n\n')
fprintf('Press any key to continue.\n\n')
pause

w4 = -5:10/1024:5-1/1024;
plot(w4,S4);
fprintf('Frequency spectrum: Sampling rate again halved.\n')
fprintf('60 rad/sec peak now appears to be much lower.\n\n')
