% Aliasing, quantization, and clipping examples
% Prepared by DRB for ECE4703 lecture on 03-Nov-2008

% ----------------------------------------------------------------------
% Sine wave ramp example
% ----------------------------------------------------------------------

% Generate an "infinite precision" sin wave ramp from 100Hz to 10100Hz.
% The sampling rate is set so that there is no aliasing.
fs=44100;                       % set sampling rate
t=0:1/fs:5;                     % make time vector
x1=sin(2*pi*(100+1000*t).*t);   % make frequency ramp
soundsc(x1,fs);                 % listen to it
pause

% Aliasing example 1
% Here we generate the same waveform at a lower sampling
% frequency - one that does not satisfy the sampling theorem
fs2=8000;                       % set sampling rate
t=0:1/fs2:5;                     % make time vector
x2=sin(2*pi*(100+1000*t).*t);   % make frequency ramp
soundsc(x2,fs2);                % listen to it
pause

% Aliasing example 2
% Here we take the original waveform and use the Matlab function resample
% This function applies an antialaising filter before converting the
% data to the lower sampling rate
% Note that most of the aliasing is removed but some still gets
% through the AAF
x3=resample(x1,80,441);         % resample to 8000Hz
soundsc(x3,fs2);                % listen to it
pause

% Quantization example
% Here we quantize the original "infinite precision" waveform to
% a much lower resolution in order to hear the effect of extreme
% quantization
bits=4;                         % set number of bits
x4=round(x1*2^(bits-1))/2^(bits-1); % quantize
soundsc(x4,fs);                 % listen to it
pause

% Clipping example
% Here we scale the signal so that it is 1.3x the full range of the ADC
bits=16;                         % set number of bits
x5 = x1*2;
vref = 1;
i1 = find(x5>vref*(2^(bits-1)-1)/(2^(bits-1)));
x5(i1) = vref*(2^(bits-1)-1)/(2^(bits-1));
i2 = find(x5<-vref);
x5(i2) = -vref;
soundsc(x5,fs);                 % listen to it
