Lab Manuals
Lab Manuals
Lab Manuals
by Martin Bouchard
M. Bouchard, 2009
a), plot the real and imaginary parts of the response to the complex exponential x[n]=
n u[n]
e 3
j
(using filter, real and imag functions). Use a long enough section of the input
section so that the transient has died out. Find the steady state amplitude gain
of the
=0 and = / 3 . Compare
n)
3
and compare the output with the gain found in f). Plot the input and output signals.
M. Bouchard, 2009
1
.
1 2r cos z 1 r 2 z 2
Provide an approximate relation between r, and the frequency of the resonant peak in
H ( e j )
c) Write a script to show the magnitude of the frequency response of the system. Use
some values of r in the range 0.7 < r < 1.0, and for each value find the frequency
response using freqz. Use a constant value of
M. Bouchard, 2009
1 2 cos z 1 z 2
1 1.8 cos z 1 0.81z 2
Plot the frequency response for 2 / 5 and verify that it is a notch filter.
f) If this filter/system is used to eliminate a component at 60 Hz in a signal that was
sampled at 1000 Hz, what is the value required ? What will be the (approximate) gain
of the filter at the other frequencies ?
g) Generate a 60 Hz sinusoid samples at 1000 Hz sampling rate. Filter this signal by the
notch filter and verify that it eliminates the 60 Hz component. Plot the different signals.
M. Bouchard, 2009
possible to illustrate the aliasing. For an interval of 10 ms, plot the sampled sine wave if
f 0 = 300 Hz, using stem. The phase can be arbitrary. You should see a sinusoidal
pattern. If not, use the plot function which creates the impression of a continuous function
from discrete time values.
b) Vary the frequency f 0 from 100 Hz to 475 Hz, in steps of 125 Hz. The apparent
frequency of the sinusoid should be increasing, as expected. Use subplot to put four plots
on one screen.
c) Vary the frequency f 0 from 7525 Hz to 7900 Hz, in steps of 125 Hz. Note that the
apparent frequency of the sinusoid is now decreasing. Explain why.
d) Vary the frequency f 0 from 32100 Hz to 32475 Hz, in steps of 125 Hz. Can you
predict in advance if the frequency will increase or decrease ? Why/How ?
2) Frequency domain representation of sampling and aliasing, A/D and D/A
convertions
M. Bouchard, 2009
Plot as a continuous function 1000 samples of the resulting signal when the frequency
f 0 is 2 kHz.
f) Plot the continuous time Fourier transform (amplitude) of the signal using the
following function, where dt is the time resolution :
function freqmagplot(x,dt)
L=length(x);
Nfft=round(2.^round(log2(5*L)));
X=fft(x,Nfft);
f=((1/dt)/Nfft)*(0:1:Nfft/2-1);
plot(f,abs(X(1:Nfft/2)));
title('Magnitude of Fourier Transform');
xlabel('Frequency'),grid;
This function simulates a discrete time or a continuous time Fourier Transform by
computing a DFT/FFT with a high resolution.
g) To simulate the A/D conversion at a rate of f s = 8000 Hz (sampling period of 1/8000
second), we need to keep one sample in every 10 samples from the signal in e). Plot the
resulting discrete time signal and its discrete time Fourier transform (again freqmagplot
can be used, but with the appropriate value for dt !).
h) To simulate the D/A conversion, we need to follow two steps. In the first step, the
discrete time signal from g) is converted to an analog pulse signal. An analog pulse signal
is the ideal case, in practice the analog signal is typically the output of a sample and hold
device. To simulate the analog pulse signal, 9 zeros are added between each sample of the
discrete time signal from g), so that the resulting simulated continuous signal has the
M. Bouchard, 2009
original resolution of 1/80000 sec. Plot the resulting signal and its continuous time
Fourier transform.
i) The second step of the D/A conversion is to filter (interpolate) the signal found in h), so
that the samples with zero values can be filled with non-zero values. In the frequency
domain, this means low-pass filtering the continuous Fourier transform found in h) so
that only the first peak remains. The resulting Fourier transform should be almost
identical to the transform found in f). To perform the low-pass filtering, use the following
filter coefficients
[b,a]=cheby2(9,60, f s *1/80000);
and the function filter. Plot the signal at the output if the filter, discard the first 200
samples (transient response) and plot the continuous time Fourier transform of the
resulting signal. Compare with f).
j) Repeat the steps in e) f) g) h) i) with f 0 = 2500 Hz, 3500 Hz, 4500 Hz, 5500 Hz (plots
not required here). When does aliasing occurs ? What is the effect of aliasing on the
output signal of the D/A converter (found in i) ) ?
M. Bouchard, 2009
Assignment #4 : Windowing
A window acts in the time domain by truncating the length of a signal :
y[n]=x[n] w[n],
1
2
spectrum of x[n], and this difference should be minimized by the choice of a proper
window.
a) When only the values of x[n] in the interval 0 n L-1 are kept, but there is no
weighting function w[n] applied to x[n], then the window function w[n] is called
rectangular or uniform (i.e. w[n]=1
boxcar in Matlab. Compute the DTFT of a rectangular window w[n] of length 21, using
freqmagplot with dt=1. Plot the magnitude on a dB scale or a linear scale.
b) Repeat for a length of 16, 31 and 61 coefficients. What is the effect of the window
length on the size of the mainlobe and on the amplitude of the sidelobes (relative to the
mainlobe amplitude)?
c) A triangular window (also called Bartlett window) can be generated using the triang
function. Generate the DTFT for triangular windows of length 31 and 61, and plot the
magnitude response in dB. Compare with the results from a) and b).
d) Since a triangular window can be seen as the convolution of two smaller rectangular
windows, explain the difference in mainlobe width for the rectangular and triangular
windows.
M. Bouchard, 2009
e) The Hamming, von Hann (Hanning) and Blackman windows can be generated in
Matlab using the hamming, hanning and blackman functions. Plot on the same graph the
Hamming, Hanning and Blackman windows for a length of 31. Plot on the same graph
the magnitude of the DTFT (again estimated by a DFT/FFT) of these windows, and the
DTFT of the rectangular window. Compare the width of the mainlobes and the amplitude
of the sidelobes. Zoom in the low-frequency part of the spectrum if you want to see more
clearly the mainlobes.
f) The Kaiser window (found using the kaiser function) is widely used for the design of
simple FIR filters. In the Kaiser window, there is a parameter that offers a trade-off
between the sidelobes height and the width of the mainlobe. A value between 0 and 10
should be used in practice. Generate three Kaiser windows of length 31. Try different
values of : 3, 5 and 8. Plot the coefficients on one graph. Compute the DTFTs of these
windows and plot the magnitude (in dB) on these windows on one graph. Comment on
the effect of and compare the Kaiser windows with the Hamming window.
g) An important notion in spectrum analysis is the notion of resolution. It is important to
understand that the spectral resolution caused by a windowing operation is totally
different from the spectral resolution of a DFT/FFT. The loss of resolution caused by
windowing directly affects the DTFT, and therefore it is not caused by the DFT/FFT
sampling of the DTFT. When a large size DFT/FFT is used (using zero padding), the
main factor that will limit the spectral resolution is the windowing operation, and not the
DFT/FFT operation. Generate 64 samples of the following signal, choosing distinct
values for 1 and 2 :
x[n]=cos( 1 n)+cos( 2 n + 0.4).
Using freqmagplot (see assignment # 2), compute the DTFT of x[n] and plot the
magnitude. Find how small can the difference between the angular frequencies 1 and
2 be and still see two separate peaks in the DTFT. This difference is a rough estimate
M. Bouchard, 2009
of the resolution. As a starting point, you can choose values in the neighborhood of
h) Repeat g) for window lengths of 128 and 256 samples. What are the resulting
resolutions ?
i) For a window length of 128, find the resolution (as in g) ) of the Hanning, Hamming
and Blackman windows, using the same signal x[n]=cos( 1 n)+cos( 2 n + 0.4).
10
M. Bouchard, 2009
e j M
2
len
lines :
M=(len-1)/2;
k=[0:len-1];
pd=exp(-2*pi*j*M*k/len);
The resulting desired sampled frequency response is simply : Hd=Ad.*pd. Using the
inverse FFT, find and plot the impulse response h[n] that will produce the sampled
frequency response. h[n] should be real and symetric. If h has a small imaginary
component that should be neglected, then just use h=real(h) to keep the real part. If the
imaginary component is not small, then you have made a mistake.
b) Now find the real (i.e. not sampled) frequency response of the filter, using freqz. Plot
the magnitude and compare with the ideal sampled magnitude Ad. Plot the phase of the
frequency response using angle and unwrap. Where do jumps occur in the phase
frequency response ?
11
M. Bouchard, 2009
. Compare the amount of overshoot near the band edge with the design for
len=23.
Design with window functions
h) Design a length-23 linear-phase FIR low-pass filter with a passband edge of
0 0.3 radians/sample using a window approach. Do not use a frequency sampling
technique as in a). Use the windowing approach with the following windows: rectangular,
Hanning, Hamming and Kaiser with 6 . Find the frequency response of the resulting
filters, and compare with the filter found in a).
12
M. Bouchard, 2009
remez Matlab function (you can also use the remezord function). What is the particular
characteristic of the magnitude of the filter frequency response
13
M. Bouchard, 2009
14
M. Bouchard, 2009
magnitude of the frequency responses found in a) b) c) and d), explain intuitively why the
elliptic filter always have the lowest order (low order as a compromise of ...).
f) For the specifications in e), design a FIR Chebyshev/Parks-McClellan/Remez low-pass
filter, using remez and remezord functions. Verify the frequency response of the designed
filter. Compare the required order for this FIR filter with the orders of the IIR filters
found in e).Discuss.
Bilinear transform
g) It is desired to design a digital low-pass 4 th order Butterworth filter with a sampling
frequency of 40 kHz and a passband edge of 8 kHz, using an analog filter and the bilinear
transformation. Find the required discrete time passband edge frequency. Then find the
prewarped analog passband edge that is required if the bilinear transformation is going to
be applied to the analog filter.
h) Design the low-pass analog 4th order Butterworth filter using the passband edge found
in g) and the function butter(N,Wn,'s'). Verify the frequency response and stability (via
the impulse response), using the freqs and impulse(b,a,Tf) functions for analog systems.
i) Using the [b2,a2] = bilinear(b,a,Fs) command, transform the continuous time filter to
a discrete time filter. Check the frequency response of the digital filter. Does it meet the
specifications ? Design an equivalent filter directly in the discrete time domain using
butter, and compare the results.
Design of filters by frequency transformation
j) It is possible to directly design a digital IIR highpass, bandpass or band reject filter
using the butter, cheby1, cheby2 and ellip functions. Design a 5th order Chebyshev type I
bandpass filter with a sampling frequency of 20 Hz, a lower passband edge of 5 Hz, an
upper passband edge of 8 Hz, and a passband ripple of 1 dB. Plot the frequency response
and the impulse response.
15
M. Bouchard, 2009
k) The different steps performed in the design of the digital bandpass filter in j) will now
be illustrated. First, design an analog 5th order Chebyshev type I lowpass filter with a
passband ripple of 1 dB and a unity passband edge frequency. Plot the frequency
response of the filter. Then convert it to an analog bandpass filter using the
s 2 1 2 s 2 0 2
transformation (lp2bp function). 1 , 2 are the passband
s
s( 2 1 ) s BW
edge frequencies of the analog bandpass filter, and they are computed from the edge
frequencies of the desired bandpass digital filter using the bilinear transformation. Plot
the frequency response of the filter. After the analog bandpass filter is designed, convert it
to a digital filter using the bilinear function. Plot the frequency response of the digital
filter, and compare it with the response found in j).
16
M. Bouchard, 2009
2 6 .
Using a small
step size will simulate in Matlab the continuous amplitude of a non-quantized signal.
Generate a quantized version vq[n], using the function fixedpointquant :
function X = fixedpointquant( s, bit, rmode, lmode )
%fixedpointquant simulated fixed-point quantization
%------% Usage: X = fixedpointquant( S, BIT, RMODE, LMODE )
%
%
returns the input signal S reduced to a word-length
%
of BIT bits and limited to the range [-1,1). The type of
%
word-length reduction and limitation may be chosen with
%
RMODE: 'round'
rounding to nearest level
%
'trunc'
2's complement truncation
%
LMODE: 'sat'
saturation limiter
%
'overfl'
2's complement overflow
if nargin ~= 4;
error('usage: fxquant( S, BIT, RMODE, LMODE ).');
end;
if bit <= 0 | abs(rem(bit,1)) > eps;
error('wordlength must be positive integer.');
end;
Plus1 = 2^(bit-1);
X = s * Plus1;
if strcmp(rmode, 'round');
X = round(X);
elseif strcmp(rmode, 'trunc');
X = floor(X);
else
error('unknown wordlength reduction spec.');
end;
if strcmp(lmode, 'sat');
17
M. Bouchard, 2009
X = min(Plus1 - 1,X);
X = max(-Plus1,X);
elseif strcmp(lmode, 'overfl');
X = X + Plus1 * ( 1 - 2*floor((min(min(X),0))/2/Plus1) );
X = rem(X,2*Plus1) - Plus1;
else error('unknown limiter spec.');
end;
X = X / Plus1;
This function simulates the fixed point quantization in the interval [-1.0 1.0] of a nonquantized signal. Use a wordlength of 3 bits with the function, with a rounding and a
saturation for the quantizer. Compute e[n]=vq[n]-v[n], and plot vq[n] versus v[n], and
e[n] versus v[n]. What are the statistical properties of the error e[n] (mean, max.,
distribution) ?
b) Generate a Gaussion random input signal with zero mean and variance S of 0.01, using
randn with 10000 samples. Quantize the signal using fixedpointquant, with various word
length (number of bits). Find the S/N ratio in dB (energy of v[n] / energy of e[n]) for each
wordlength, and find the improvement in the S/N ratio provided by an additional bit.
c) For small values of variance S and a fixed number of bits, the S/N ratio will linearly
increase with S (because the variance of the quantization noise is constant). However, for
large values of the variance S (S=0.5 for example), the S/N ratio will not increase with an
increase in S. What happens in this case ? Hint : check the e[n] and vq[n] signals.
d) Repeat a) by using a 2's complement truncation quantizer instead of a rounding
quantizer. Compare the mean, the maximum and the distribution of the error signal e[n]
with the one found in a).
e) Finite word effects also affect the performance of digital filters. All filter structures
have the same input-output behavior when unlimited wordlength is used, but this is not
the case in practice, and some structures produce much better results in finite word
environments. For fixed point implementations of filters, the coefficients must have a
quantized amplitude in the [-1.0 1.0] interval. Therefore, after a design step the
18
M. Bouchard, 2009
coefficients have to be scaled to fit in this interval. This will affect the gain of the filter,
and therefore an inverse scaling is required at the output of the filter. The coefficients can
be scaled using the function quantizecoeffs :
function [aq,nfa] = quantizecoeffs(a,w);
f=log(max(abs(a)))/log(2); % normalisation by n, a power of 2, so that all coeffs
n=2^ceil(f);
% are in the interval [-1 1]
an=a/n;
aq= fixedpointquant(an,w,round,sat);
nfa=n;
Using the FIR half-band low-pass filter obtained with b=remez(30,[0 0.4 0.6 1], [1 1 0
0]), compute the frequency response of the un-quantized coefficients using freqz.
f) Quantize the coefficients from e) using quantizecoeffs with 6, 10, 16 bits wordlengths.
Compare the frequency response of the quantized filter in the passband and the stopband
with the frequency response of the un-quantized filter.
g) Does the quantization of the coefficients in the direct form structure destroy the linear
phase property of FIR linear phase un-quantized filters ? Why ?
h) Plot using freqz the frequency response of the IIR low-pass elliptic filter obtained with
[b,a]=ellip(7, 0.1, 40, 0.4).
i) Quantize the coefficients of the IIR filter using the quantizecoeffs function, with 6, 10
and 16 bits wordlengths. Plot the frequency response in each case. What do you observe ?
Explain.
j) Coefficients of the cascade form can be found using the following instructions :
[b,a]=ellip(7, 0.1, 40, 0.4)
[Z,p,k] = TF2ZP(b,a);
sos=ZP2SOS(Z,p,k);
% direct form
% zero-pole form
% cascade form
19
M. Bouchard, 2009
Each row of the matrix sos contains 6 elements. The first 3 elements are the coefficients
of the numerator in a second order section of a cascade system, while the last 3 elements
are the denominator coefficients. Compute the frequency response of each section using
freqz, and find the global frequency response of the system. Verify that it is the same as in
h). Hint : to combine the frequency response of the sections, you can use the following
approach :
h=zeros(1000,N);
g=ones(1000,1);
for(i=1:1:N)
[h(:,i),w]=freqz(sos(i,1:3), sos(i,4:6),1000);
g(:,1)=g(:,1).*h(:,i);
end
k) Quantize the coefficients of each section of the cascade structure using quantizecoeffs
with 6, 10, 16 bits wordlengths. Compute the frequency response of each section using
freqz, and find the global frequency response of the system. Compare your results with
the results from i).
20
M. Bouchard, 2009
3
] interval). Design a half-band highpass FIR filter with a length of
2
50. Filter the 2050 samples by the FIR filter, and keep the 2000 last values of the output
samples. Multiply the resulting signal by
21
n
2 .
M. Bouchard, 2009
factor of 2, thus keeping only 1000 values. Perform the FFT of those values, and plot the
magnitude of the FFT values. Compare with the middle (high frequencies) FFT values
found in d). You should get similar values and similar resolutions. Explain analytically
(with graphs) the process that was performed. The same process could also be applied to
zoom low frequency values. In fact, if the spectrum is divided in D parts, with D integer,
a zoom can be performed on any part using filtering, modulation and decimation.
22
M. Bouchard, 2009