Vous êtes sur la page 1sur 112

E E 2 7 5 Lab September 1, 2006

LAB 1. Signals in Matlab


Introduction
This lab will describe how to use Matlab for some basic signal representation and manipu-
lation:
Creating and importing signals
Sampling and resampling
Signal visualization
Modeling noise
Modulation
Discrete Signals
Time base: t = [0.0 0.1 0.2 0.3]
Signal data: x = [1.0 3.2 2.0 8.5]
The central data construct in Matlab is the numeric array, an ordered collection of real
or complex numeric data with one or more dimensions. The basic data objects of signal
processing (one-dimensional signals or sequences, multichannel signals, and two-dimensional
signals) are all naturally suited to array representation.
Matlab represents ordinary one-dimensional sampled data signals, or sequences, as vectors.
Vectors are 1-by-n or n-by-1 arrays, where n is the number of samples in the sequence.
One way to introduce a sequence into Matlab is to enter it as a list of elements at the com-
mand prompt. The statement
x = [1 2 3 4 5]
creates a simple ve-element real sequence in a row vector. It can be converted to a column
vector by taking the transpose:
x = [1 2 3 4 5]
Column vectors extend naturally to the multichannel case, where each channel is represented
by a column of an array.
c 2006GM
Another method for creating vector data is to use the colon operator. Consider a 1-second
signal sampled at 1000 Hz. An appropriate time vector would be
t = 0:1e-3:1;
where the colon operator creates a 1001-element row vector representing time from zero to
one second in steps of one millisecond.
You can also use linspace to create vector data:
t = linspace(0,1,1e3);
creates a vector of 1000 linearly spaced points between 0 and 1.
Try:
t1 = [0 .1 .2 .3];
t2 = 0:0.1:0.3;
t3 = linspace(0, 0.3, 4);
T = [t1 t2 t3];
X = sin(T)
Q: What does this code show?
Sampling Signals
Analog signal sources include electromagnetic, audio, sonar, biomedical and others. Analog
signals must be sampled in order to be processed digitally.
Sampling
x(n) = x
a
(nT
s
)
x is a discrete signal sampled from the analog signal x
a
with a sample period of T
s
and a
sample frequency of F
s
= 1/T
s
.
Try:
Fs = 100;
N = 1000;
stoptime = 9.99;
t1 = (0:N-1)/Fs;
t2 = 0:1/Fs:stoptime;
x1 = sin(2*pi*2*t1);
x2 = sin(2*pi*3*t2);
plot(x1)
figure, plot(x2)
An alternative to creating signals is to use a toolbox function. A variety of toolbox functions
generate waveforms . Each of them requires that you begin with a vector representing a time
base. Some of these functions will be described later in this lab.
Aliasing
Digital signals are often derived by sampling a continuous-time signal with an analog-to-
digital (A/D) converter. If the continuous signal, x
a
(t), is bandlimited, meaning that it does
not contain any frequencies higher than a maximum frequency f
M
, the Shannon sampling
theorem says that it can be completely recovered from a set of samples if the sampling
frequency f
s
is greater than two times the maximum frequency of the signal to be sampled:
F
s
> 2f
M
This maximum frequency f
M
is known as the Nyquist frequency. If the sampling frequency is
not greater than two times the Nyquist frequency, the continuous signal cannot be uniquely
recovered and aliasing occurs. (You heard examples of aliased signals in Homework No.1).
f
s
> 2f
M
: Original signal and sampled signal have the same frequency.
f
s
2f
M
: Sampled signal is aliased to half the original frequency.
Try:
t = 0:0.001:2;
xa = sin(2*pi*5*t);
plot(t,xa)
hold on
fs = 15;
ts = 0:1/fs:2;
xs1 = sin(2*pi*5*ts);
plot(ts,xs1,ro-)
fs = 7.5;
ts = 0:1/fs:2;
xs2 = sin(2*pi*5*ts);
plot(ts,xs2,ro-)
hold off
Q: What is the frequency of xs2?// (There is aliasing here. We need sampling theory.
However can use the t function on the signal to determine the frequency).
Signal Visualization
View signal amplitude vs. time index
Functions: plot, stem, stairs, strips
Listen to data: sound
Note: the sound and soundsc commands will not work if your computer hardware isnt set
up. If that is the case, view the signals instead of listening to them.
Try:
t = [0.1 0.2 0.3 0.4];
x = [1.0 8.0 4.5 9.7];
plot(t,x)
figure, stem(t,x)
figure, stairs(t,x)
fs = 1000;
ts = 0:1/fs:2;
f = 250 + 240*sin(2*pi*ts);
x = sin(2*pi*f.*ts);
strips(x,0.25,fs)
sound(x,fs)
plot(ts,x)
plot(ts(1:200),x(1:200))
Q: What does the strips command do? (See help strips.)
Q: What does the .* operator do?
Signal Processing Tool
The Signal Processing Toolbox application, SPTool, provides a rich graphical environment
for signal viewing, lter design, and spectral analysis.
You can use SPTool to analyze signals, design lters, analyze lters, lter signals, and an-
alyze signal spectra. You can accomplish these tasks using four GUIs that you access from
within SPTool:
The Signal Browser is for analyzing signals. You can also play portions of signals using
your computers audio hardware.
The Filter Designer is for designing or editing FIR and IIR digital lters. Note that the
FDATool is the preferred GUI to use for lter designs. FDATool is discussed in later labs.
The Filter Viewer is for analyzing lter characteristics.
The Spectrum Viewer is for spectral analysis.
Open SPTool by typing sptool at the command prompt.
Try:
sptool
Look at the train signal, FIRbp lter, and trainse spectrum. (You see 3 panes
- Signals, Filters, Spectra. Filter Designer is available through File Preferences. You
can play sounds using the LS icon. When viewing spectra, note that many methods of
determining spectra, including the t, are available.)
Importing a Signal
You can use SPTool to analyze the signals, lters, or spectra that you create at the Matlab
command line.
You can import signals, lters, or spectra from the Matlab workspace into the SPTool
workspace using the Import item under the File menu.
Try:
fs = 1000;
ts = 0:1/fs:0.5;
f = 250 + 240*sin(2*pi*ts);
x = sin(2*pi*f.*ts);
Import these signals (f and x) into the SPTool and use the tool to examine them.
Q: What are the icons to use for horizontal zoom?
Try zooming in using the mouse.
Signal Browser
The Signal Browser tool is an interactive signal exploration environment. It provides a
graphical view of the signal object(s) currently selected in teh Signals list of SPTool.
Using the Signal Browser you can
View and compare vector/array signals
Zoom in on a range of signal data to examine it more closely
Measure a variety of characteristics of signal data
Play signal data on audio hardware
To open/activate the Signal Browser for the SPTool,
Click one or more signals (use the Shift key for multiple selections) in the Signals list of
SPTool.
Click the View button in the Signals list of SPTool.
Changing Sample Rates
To change the sample rate of a signal in SPTool,
1. Click a signal in the Signals list in SPTool.
2. Select the Sampling frequency item in the Edit menu.
3. Enter the desired sampling frequency and cliick OK.
Try changing the sampling rate of the imported signal.
Signal Generation
Signals
Create a time base vector
t = [0:0.1:2];
Create a signal as a function of time
x = sin(pi*t/2);
plot(t,x)
Useful Matlab functions
Nonperiodic functions
ones, zeros
Periodic functions
sin, cos, square, sawtooth
Nonperiodic Signals
t = linspace(0,1,11)
Step:
y = ones(1,11);
stem(y)
Impulse:
y = [1 zeros(1,10)];
stem(y)
Ramp:
y = 2*t;
plot(y)
Useful Matlab functions
step, impulse, gensig
Try:
Step function:
fs = 10;
ts = [0:1/fs:5 5:1/fs:10];
x = [zeros(1,51) ones(1,51)];
stairs(ts,x)
Impulse function with width w:
fs = 10;
w = 0.1;
ts = [-1:1/fs:-w 0 w:1/fs:1];
x = [zeros(1,10) 1 zeros(1,10)];
plot(ts,x)
Delta function:
ts = 0:0.5:5;
x = [1 zeros(1,length(ts)-1)];
stem(ts,x)
axis([-1 6 0 2])
Sinusoids
Sinusoid parameters
Amplitude, A
Frequency, f
Phase shift,
Vertical oset, B
The general form of a sine wave is
y = Asin(2ft + ) + B
Example: generate a sine wave given the following specications:
A = 5
f = 2 Hz
= /8 radians
t = linspace(0,1,1001);
A = 5;
f = 2;
p = pi/8;
sinewave = A*sin(2*pi*f*t + p);
plot(t, sinewave)
Try:
edit sine_wave
sine_wave
edit sinfun
[A T] = sinfun(1,2,3,4)
Square Waves
Square wave generation is like sine wave generation, but you specify a duty cycle, which is
the percentage of the time over one period that the amplitude is high.
Example:
duty cycle is 50% (the Matlab default)
frequency is 4 Hz.
t = linspace(0,1,1001);
sqw1 = square(2*pi*4*t);
plot(t,sqw1)
axis([-0.1 1.1 -1.1 1.1])
Example:
duty cycle is 75%
frequency is 4 Hz.
t = linspace(0,1,1001);
sqw2 = square(2*pi*4*t,75);
plot(t,sqw2)
axis([-0.1 1.1 -1.1 1.1])
Sawtooth Waves
Sawtooth waves are like square waves except that instead of specifying a duty cycle, you
specify the location of the peak of the sawtooth.
Example:
peak at the end of the period (the Matlab default)
frequency is 3 Hz.
t = linspace(0,1,1001);
saw1 = sawtooth(2*pi*3*t);
plot(t,saw1)
Example:
peak is halfway through the period
frequency is 3 Hz.
t = linspace(0,1,1001);
saw2 = sawtooth(2*pi*3*t,1/2);
plot(t,saw2)
Complex Signals
Periodic signals can be represented by complex exponentials:
x(t) = e
j2ft
= cos(2ft) + jsin(2ft) = cos(t) + jsin(t)
If t is measured in seconds, then f will have units of sec
1
, and will have units of radi-
ans/second.
In signal processing, we associate the unit circle with one sampling cycle, so that a sampling
frequency of F
s
is associated with 2 radians, and the Nyquist frequency F
s
/2 is associated
with radians. Values of in the upper half-plane, in units of Hz, then correspond to
frequencies within the sampled signal.
In Matlab, type:
x = exp(2*pi*j*f*t);
plot(x)
Matlab recognizes either j or i as the square root of -1, unless you have dened variables j
or i with dierent values.
Useful Matlab functions
real, imag, abs, angle
Try:
edit zsig
zsig(5)
Look at both gures and describe what you see.
Importing Data
An important component of the Matlab environment is the ability to read and write data
from/to external sources. Matlab has extensive capabilities for interfacing directly with data
from external programs and instrumentation.
In this lab, we concentrate on reading and writing data that has already been stored in
external les.
Files come in a variety of standard formats, and Matlab has specialized routines for working
with each of them. To see a list of supported le formats, type:
help fileformats
To see a list of associated I/O functions, type:
help iofun
Matlab provides a graphical user interface, the Import Wizard, to the various I/O functions.
You access the Wizard by choosing File Import Data or by typing:
uiimport
The Matlab command importdata is a programmatic version of the Wizard, accepting all of
the default choices without opening the graphical user interface. You can use importdata in
M-les to read in data from any of the supported le formats.
Matlab also has a large selection of low-level le I/O functions, modeled after those in the C
programming language. These allow you to work with unsupported formats by instructing
Matlab to open a le in memory, position itself within the le, read or write specic formatted
data, and then close the le.
Try:
help fileformats
help iofun
jan = textread(all_temps.txt,%*u%u%*[^\n],headerlines,4);
[data text] = xlsread(stockdata.xls);
plot(data(:,2))
legend(text{1,3})
Explain how the colon operator works in the preceding plot command.
I = importdata(eli.jpg);
image(I)
which theme.wav
uiimport
Browse for:
theme.wav
soundsc(data,fs)
Save and Load
Two data I/O functions are especially useful when working with Matlab variables.
The save command writes workspace variables to a binary Matlab data le (MAT-le)
with a .mat extension. The le is placed in the current directory.
The load command reads variables from a MAT-le back into the Matlab workspace.
Although quite specialized, save and load can be used for day-to-day management of your
Matlab computations.
Try:
doc save
doc load
t = 0:0.1:10;
x1 = sin(t);
x2 = sin(2*t);
x3 = sin(3*t);
save myvars
clear
load myvars t x3
Note the list of variables in the workspace tab in the upper left of the Matlab window.
Modeling Noise
To model signals in space, in the atmosphere, in sea water, or in any communications channel,
it is necessary to model noise.
Matlab has two functions for generating random numbers, which can be added to signals to
model noise.
Uniform random numbers
A = rand(m,n);
generates an mxn array of random numbers from the uniform distribution on the interval
[0,1]. To generate uniformly distributed random numbers from the interval [a,b], shift and
stretch:
A = a + (b-a)*rand(m,n);
Gaussian random numbers
A = randn(m,n);
generates an mxn array of random numbers from the standard normal distribution with
mean 0 and standard deviation 1. To generate random numbers from a normal distribution
with mean mu and standard deviation sigma, shift and stretch:
A = mu + sigma*rand(m,n);
Random numbers from other distributions
Random numbers from other distributions can be generated using the uniform random num-
ber generator and knowledge of the distributions inverse cumulative distribution function.
Random number generators for several dozen common distributions are available in the
Statistics Toolbox.
Adding Noise to a Signal
noisy signal = signal + noise
y1 = x + rand(size(x)) % uniform noise
y2 = x + randn(size(x)) % Gaussian noise
Example:
Add Gaussian noise to middle C.
fs = 1e4;
t = 0:1/fs:5;
sw = sin(2*pi*262.62*t); % middle C
n = 0.1*randnsize(sw);
swn = sw + n:
Try:
edit noisyC
noisyC
strips(swn, .1,1e4)
Zoom in on the strips plot. (Note: you might have to cut and paste from the noisyC script
to generate swn.)
Pseudorandomness
This number:
0.95012928514718
is the rst number produced by the Matlab uniform random number generator with its
default settings. Start up Matlab, set format long, type rand, and you get the number.
If all Matlab users, all around the world, all on dierent computers, keep getting this same
number, is it really random? No, it isnt. Computers are deterministic machines and
should not exhibit random behavior. If your computer doesnt access some external de-
vice, like a gamma ray counter or a clock, then it must really be computing pseudorandom
numbers.
A working denition of randomness was given in 1951 by Berkeley professor D. H. Lehmer,
a pioneer in computing and, especially, computational number theory:
A random sequence is a vague notion ... in which each term is unpredictable
to the uninitiated and whose digits pass a certain number of tests traditional with
statisticians ...
Random number generators proceed deterministically from their current state. To view the
current state of rand, type:
s = rand(state)
This returns a 35-element vector containing the current state.
To change the state of rand:
rand(state,s) Sets the state to s.
rand(state,0) Resets the generator to its initial state.
rand(state, sum(100*clock)) Sets to a new state each time.
Commands for randn are analogous.
Try:
s = rand(state)
format long
rand
rand(state,sum(100*clock))
s = rand(state)
format long
rand
Resampling
The Signal Processing Toolbox provides a number of functions that resample a signal at a
higher or lower rate.
y = downsample(x,n)
decreases the eective sampling rate of x by keeping every nth sample starting with the rst
sample. x can be a vector or a matrix. If x is a matrix, each column is considered a separate
sequence.
y = upsample(x,n)
increases the eective sampling rate of x by inserting n1 zeros between samples. x can be
a vector or a matrix. If x is a matrix, each column is considered a separate sequence. The
upsampled y has x n samples.
y = resample(x,p,q)
resamples the sequence in vector x at p/q times the original sampling rate, using a polyphase
lter implementation. p and q must be positive integers. The length of y is equal to
ceil(length(x) p/q). If x is a matrix, resample works down the columns of x.
y = interp(x,r)
increases the sampling rate of x by a factor of r. The interpolated vector y is r times longer
than the original input x.
y = decimate(x,r)
reduces the sampling rate of x by a factor of r. The decimated vector y is r times shorter
in length than the input vector x. By default, decimate employs an eighth-order lowpass
Chebyshev Type I lter. It lters the input sequence in both the forward and reverse
directions to remove all phase distortion, eectively doubling the lter order.
Try:
load mtlb
sound(mtlb,Fs)
mtlb4 = downsample(mtlb,4)
mtlb8 = downsample(mtlb,8)
sound(mtlb8,fs/8)
What are the sizes of mtlb, mtlb4, and mtlb8?
(If sound doesnt work, plot the signals.)
t = 0:0.00025:1;
x = sin(2*pi*30*t) + sin(2*pi*60*t);
y = decimate(x,4);
subplot(211), stem(x(1:120))
axis([0 120 -2 2])
title(Original Signal)
subplot(212), stem(y(1:30))
title(Decimated Signal)
Modulation and Demodulation
Modulation varies the amplitude, phase, or frequency of a carrier signal with reference to a
message signal.
The Matlab modulate function modulates a message signal with a specied modulation
method. The syntax is
y = modulate(x,fc,fs,method)
where:
x is the message signal.
fc is the carrier frequency.
fs is the sampling frequency.
method is a ag for the desired modulation method (see table below).
Method Description
amdsb-sc or am Amplitude modulation, double side-band, suppressed carrier
amdsb-tc Amplitude modulation, double side-band, transmitted carrier
amssb Amplitude modulation, single side-band
fm Frequency modulation
pm Phase modulation
ppm Pulse position modulation
pwm Pulse width modulation
qam Quadrature amplitude modulation
The demod function performs demodulation, that is, it obtains the original message signal
from the modulated signal. The syntax is:
x = demod(y,fs,fs,method)
demod uses any of the methods shown for modulate. The signal x is attenuated relative to
y because demodulation uses lowpass ltering.
Exercise: High and Low
1. Create a signal equal to the sum of two sine waves with the following characteristics:
3-second duration
Sampling frequency = 2 kHz
Sinusoid 1: frequency 50 Hz (low), amplitude 10, phase = 0
Sinusoid 2: frequency 950 Hz (high), amplitude 1, phase = 0
2. View and listen to the signal using an M-le
3. Import the signal into SPTool and view it. Listen to the signal.
HAND IN:
ANSWERS TO ALL QUESTIONS STARTING WITH THE LETTER Q IN
FRONT OF IT.
(The material in this lab handout was put together by Paul Beliveau and derives principally from
the MathWorks training document MATLAB for Signal Processing, 2006.)
c 2006GM
E E 2 7 5 Lab June 30, 2006
Lab 2. Spectral Analysis in Matlab
Introduction
This lab will briey describe the following topics:
Signal statistics
Discrete Fourier Transform
Power Spectral Density estimation
Time-varying spectra
Wavelets
Statistical Signal Processing
Repeated measurements of a signal x under identical environmental conditions typically yield
dierent waveforms. The value x(n) of a signal at sample n is not a constant, but rather a
random variable with a certain distribution.
A signal is stationary if its distribution at any n is independent of time shifts, i.e., if x(n) and
x(n + N) have the same distribution for every integer N. Stationary signals are associated
with steady states in the system producing the signal, and are characterized by constant
averages and variances along the signal. When statistics computed along any instance of a
signal are identical to those computed across ensembles of dierent instances of the signal,
the system is ergodic. Ergodicity is assumed in most practical situations.
Matlab has functions for computing the mean (mean), variance (var), standard deviation
(std), covariance (cov), and correlation coecient (corrcoe) of signal values sampled across
time or across ensembles. The Statistics Toolbox provides many additional statistical func-
tions.
The Signal Processing Toolbox provides a crosscorrelation function (xcorr) and a crossco-
variance function (xcov). Crosscorrelation of two signals is equivalent to the convolution of
the two signals with one of them reversed in time. The xcorr function adds several options
to the standard Matlab conv function. The xcov function simply subtracts the mean of the
inputs before computing the crosscorrelation. The crosscorrelation of a signal with itself is
called its autocorrelation. It measures the coherence of a signal with respect to time shifts.
c 2006GM
Try:
x = randn(1,100);
w = 10;
y = conv(ones(1,w)/w,x);
avgs = y(10:99);
plot(avgs)
Ensemble averages:
w = 10;
for i = 1:w;
X(i,:) = randn(1,100);
end
AVGS = mean(X);
plot(AVGS)
x = [-1 0 1];
y = [0 1 2];
xcorr(x,y)
conv(x,fliplr(y))
xcov(x,y)
xcov(x,x)
xcov(x,y-1)
What do you notice about these vectors?
Explain why you see these results.
Example: Crosscorrelation
In a simple target ranging system, an outgoing signal x is compared with a returning signal
y. We can model y by
y(n) = x(n d) +
where is an attenuation factor, d is a time delay, and is channel noise. If T is the return
time for the signal, then x and y should be correlated at n = T. The target will be located
at a distance of vT, where v is the channel speed of the signal.
Try:
x = [zeros(1,25),1,zeros(1,25)];
subplot(311), stem(x)
y = 0.75*[zeros(1,20),x] + 0.1*randn(1,71);
subplot(312), stem(y)
[c lags] = xcorr(x,y);
subplot(313), stem(lags,c)
Does this example show the expected behavior?
Why or why not?
Discrete Fourier Transform (DFT)
It is often useful to deompose data into component frequencies. Spectral analysis gives an
alternative view of time or space-based data in the frequency domain. The computational
basis of spectral analysis is the discrete Fourier transform (DFT).
The DFT of a vector y of length n is another vector Y of length n:
Y
k+1
=
n1

j=0

jk
y
j+1
where is a complex n
th
root of unity:
= e
2i/n
This notation uses i for the complex unit, and j and k for indices that run from 0 to n 1.
The subscripts j +1 and k+1 run from 1 to n, corresponding to the range usually associated
with Matlab vectors.
Data in the vector y are assumed to be separated by a constant interval in time or space
dt = 1/Fs. Fs is called the sampling frequency of y. The coecient Y
k+1
measures the
amount of the frequency f = k(Fs/n) that is present in the data in y. The vector Y is
called the spectrum of y.
The midpoint of Y (or the point just to the right of the midpoint, if n is even), corresponding
to the frequency f = Fs/2, is called the Nyquist point. The real part of the DFT is symmetric
about the Nyquist point.
The graphical user interface fftgui allows you to explore properties of the DFT. If y is a
vector,
fftgui(y)
plots real(y), imag(y), real(fft(y)), and imag(fft(y)). You can use the mouse to move
any of the points in any of the plots, and the points in the other plots respond.
Try:
Roots of unity
edit z1roots
z1roots(3);
z1roots(7);
Explore the DFT:
delta1 = [1 zeros(1,11)];
fftgui(delta1)
delta2 = [0 1 zeros(1,10)];
fftgui(delta2)
deltaNyq = [zeros(1,6),1,zeros(1,5)];
fftgui(deltaNyq)
square = [zeros(1,4),ones(1,4),zeros(1,4)];
fftgui(square)
t = linspace(0,1,50);
periodic = sin(2*pi*t);
fftgui(periodic)
Fast Fourier Transform (FFT)
The Matlab function fft, called by fftgui, uses a fast Fourier transform algorithm to
compute the DFT.
DFTs with a million points are common in applications. For modern signal and image
processing applications, and many other applications of the DFT, the key is the ability to
do such computations rapidly. Direct application of the denition of the DFT requires n
multiplications and n additions for each of the n coecients - a total of 2n
2
oating-point
operations. This number does not include the generation of the powers of . To do a million-
point DFT, a computer capable of doing one multiplication and addition every microsecond
would require a million seconds, or about 11.5 days.
Modern FFT algorithms have computational complexity O(nlog
2
n) instead of O(n
2
). If n
is a power of 2, a one-dimensional FFT of length n requires less than 3nlog
2
n oating-point
operations. For n = 2
20
, thats a factor of almost 35,000 times faster than 2n
2
.
When using the FFT, a distinction is often made between a window length and an FFT
length. The window length is the length of the input. It might be determined by, say, the
size of an external buer. The FFT length is the length of the output, the computed DFT.
The command
Y=fft(y)
returns the DFT Y of y. The window length length(y) and the FFT length length(Y) are
the same.
The command
Y=fft(y,n)
returns the DFT Y with length n. If the length of y is less than n, y is padded with trailing
zeros to length n. If the length of y is greater than n, the sequence y is truncated. The FFT
length is then the same as the padded/truncated version of the input y.
Try:
Vector data interpolation and the origins of the FFT
edit fftinterp
fftinterp
hold off
Note: Several people discovered fast DFT algorithms independently, and many people have since
joined in their development, but it was a 1965 paper by John Tukey of Princeton University and
John Cooley of IBM Research that is generally credited as the starting point for the modern usage of
the FFT. The Matlab fft function is based on FFTW, The fastest Fourier Transform in the West,
developed by MIT graduate students Matteo Frigo and Steven G. Johnson. (http://www.tw.org)
Spectral Analysis with the FFT
The FFT allows you to estimate eciently the component frequencies in data from a discrete
set of values sampled at a xed rate. The following list shows the basic relationships among
the various quantities involved in any spectral analysis. References to time can be replaced
by references to space.
y Sampled data
n = length(y) Number of samples
Fs Samples/unit time
dt = 1/Fs Time increment
t = (0:n-1)/Fs Time range
Y = fft(y) Discrete Fourier Transform (DFT)
abs(Y) Amplitude of the DFT
abs(Y).^2/n Power of the DFT
Fs/n Frequency increment
f = (0:n-1)*(Fs/n) Frequency range
Fs/2 Nyquist frequency
A plot of the power spectrum is called a periodogram. The rst half of the principal frequency
range (from 0 to the Nyquist frequency Fs/2 is sucient, because the second half is a
reection of the rst half.
Spectra are sometimes plotted with a principal frequency range fromFs/2 to Fs/2. Matlab
provides the function fftshift to rearrange the outputs of fft and convert to a 0-centered
spectrum.
Try:
Periodograms
edit pgrams
pgrams
Whale call
edit whalefft
whalefft
FFT Demos
sigdemo1
playshow fftdemo
phone
playshow sunspots
If youre not familiar with DTMF, try the following with a touch-tone telephone. While
listening to the receiver, press two keys in the same row simultaneously, then press two keys
in the same column (e.g., 1 & 2, then 1 & 4).
Aliasing
Discrete time signals sampled from time-periodic analog signals need not be time periodic,
but they are always periodic in frequency, with a period equal to the sampling frequency.
The resulting harmonics show up as spectral copies in frequency domain plots like the pe-
riodogram. If the sampling rate is too low, these spectral copies can overlap within the
principal range, confusing the frequency analysis.
Power Spectral Density (PSD)
The power spectral density (PSD) of an analog signal y is a function of frequency, R
yy
(f),
whose area equals the total signal power. Its units are, e.g., watts/hertz, and R
yy
(f)f
approximates signal power over a small range of frequencies f centered at f. The Wiener-
Khintchine theorem states that R
yy
(f) is the DFT of the autocorrelation function r
yy
(t) of
y. The value R
yy
(0) = r
yy
(0) gives the average power in the signal.
For signals sampled over a nite interval of time, the best we can do is estimate the PSD. This
result is because the spectra of nite sequences suer from both poor resolution and leakage
(nonzero spectral components at frequencies othe than harmonics of y due to sampling over
noninteger multiples of the signal period).
PSD estimates of noisy analog signals from a nite number of its samples are based on three
fundamentally dierent approaches:
Non-parametric methods
Make no assumptions about the data in the sample and work directly with the DFT.
Welch: pwelch
Multitaper: pmtm
Parametric methods
Model the data in the sample as the output of a linear system excited by white noise (noise
with zero mean and constant PSD), estimate the lter coecients, and use these to estimate
the PSD.
Burg: pburg
Yule-Walker: pyulear
Subspace methods
Based on an eigenanalysis or eigendecomposition of the correlation matrx associated with
the data in the sample.
EV: peig
MUSIC: pmusic
Try:
Fs = 100;
t = 0:1/Fs:10;
y = sin(2*pi*15*t) + sin(2*pi*30*t);
nfft = 512;
Y = fft(y,nfft);
f = Fs*(0:nfft-1)/nfft;
Power = Y.*conj(Y)/nfft;
plot(f,Power)
title(Periodogram)
figure
ryy = xcorr(y,y);
Ryy = fft(ryy,512);
plot(f, abs(Ryy))
title(DFT of Autocorrelation)
Non-parametric Methods
Non-parametric methods estimate the PSD directly from the signal itself. The simplest such
method is the periodogram. An improved version of the periodogram is Welchs method. A
more modern technique is the multitaper method (MTM).
The following functions estimate the PSD Pxx in units of power per radians per sample.
The corresponding vector of frequencies w is computed in radians per sample, and has the
same length as Pxx.
Periodogram method
[Pxx w] = periodogram(x)
Estimates the PSD using a periodogram. Optional inputs specify windows (default is rect-
angular), FFT length, PSD sample frequencies, and output frequency range.
Welch method
[Pxx w] = pwelch(x)
Estimates the PSD using Welchs averaged periodogram method. The vector x is segmented
into equal-length sections with overlap. Trailing entries not included in the nal segment
are discarded. Each segment is windowed. Optional inputs specify windows (default is
Hamming), overlap, FFT length, and PSD sample frequencies.
Multitaper method
[Pxx w] = pmtm(x, nw)
Estimates the PSD using a sequence of 2nw1 orthogonal tapers (windows in the frequency
domain). The quantity nw is the time-bandwidth product for the discrete prolate spheroidal
sequences specifying the tapers. Optional inputs specify taper frequencies, FFT length, and
PSD sample frequencies.
Try:
t = 0:1/100:10-1/100;
x = sin(2*pi*15*t) + sin(2*pi*30*t);
periodogram(x,[],512,100);
figure
pwelch(x,[],512,100);
figure
pmtm(x,[],512,100);
Comment on the three methods.
Is one preferable to the other two?
Why or why not?
Parametric Methods
Parametric methods can yield higher resolution than non-parametric methods in cases where
the signal length is short. These methods use a dierent approach to spectral estimation:
instead of estimating the PSD directly from the data, they model the data as the output of
a linear system driven by white noise (an adaptive lter), and then attempt to estimate the
parameters of that linear system.
The most commonly used linear system model is the all-pole model, a system with all of its
zeros at the origin in the z-plane. The output of such a system for white noise input is an
autoregressive (AR) process. These methods are sometimes referred to as AR methods.
AR methods give accurate spectra for data that is peaky, that is, data with a large PSD
at certain frequencies. The data in many practical applications (such as speech) tends to
have peaky spectra, so that AR models are often useful. In addition, the AR models lead to
a system of linear equations that is relatively simple to solve.
The following methods are summarized on the next page. The input p species the order of
the autoregressive (AR) prediction model.
Yule-Walker AR method
[Pxx f] = pyulear(x,p,nfft,fs)
Burg method
[Pxx f] = pburg(x,p,nfft,fs)
Covariance and modied covariance methods
[Pxx f] = pcov(x,p,nfft,fs)
[Pxx f] = pmcov(x,p,nfft,fs)
Try:
edit pmethods
pmethods(pyulear,25,1024)
pmethods(pburg,25,1024)
pmethods(pcov,5,512)
pmethods(pmcov,5,512)
Some of the factors to consider when choosing among parametric methods are summarized
in the following table. See the documentation for further details.
Burg Covariance Modied Yule-Walker
Covariance
Characteristics
Does not apply Does not apply Does not apply Applies window
window to data window to data window to data to data
Minimizes forward Minimizes forward Minimizes forward Minimizes forward
and backward prediction error and backward prediction error
prediction errors prediction errors
Advantages
High resolution for Better resolution High resolution for As good as other
short data records than Y-W for short short data records methods for large
data records data records
Always produces Extract frequencies Extract frequencies Always produces
a stable model from mix of p or from mix of p or a stable model
more sinusoids more sinusoids
No spectral
line-splitting
Disadvantages
Peak locations Can produce Can produce Performs relatively
highly dependent unstable models unstable models poorly for short
on initial phase data records
Spectral line- Frequency bias Peak locations Frequency bias
splitting for for estimates of slightly dependent for estimates of
sinusoids in noise, sinusoids in noise on initial phase sinusiods in noise
or when order is
very large
Frequency bias for Minor frequency
sinusoids in noise bias for sinusiods
in noise
Conditions for Nonsingularity
p must be 1/2 p must be 2/3 Autocorrelation
input frame size input frame size matrix always
positive-denite,
nonsingular
Subspace Methods
Subspace methods, also known as high-resolution methods or super-resolution methods, gen-
erate PSD estimates based on an eigenanalysis or eigendecomposition of the correlation
matrix. These methods are best suited for line spectra - i.e., spectra of sinusoidal signals -
and are eective for detecting sinusoids buried in noise, especially when signal to noise ratios
are low.
The following functions estimate the pseudospectrum S (an indicateor of the presence of
sinusoidal components in a signal) of the input signal x, and a vector w of normalized
frequencies (in rad/sample) at which the pseudospectrum is evealuated. The input p controls
the dimensions of the signal and noise subspaces used by the algorithms.
Eigenvector method
[S f] = peig(x,p,nfft,fs)
Multiple Signal Classication (MUSIC) method
[S f] = pmusic(x,p,nfft,fs)
The MUSIC algorithm uses Schmidts eigenspace analysis method. The eigenvector uses a
weighted version of the MUSIC algorithm.
Try:
edit ssmethod
ssmethod(3)
ssmethod(4)
Spectrum Viewer in SPTool
The SPTool allows you to view and analyze spectra using dierent methods. To create a
spectrum in SPTool,
1. Select the signal in the Signals list in SPTool.
2. Select the Create button under the Spectra list.
Use the View button under the Spectra list in the SPTool GUI to display one or more
selected spectra.
Try:
t = 0:1/100:10-1/100;
x = sin(2*pi*15*t) + sin(2*pi*30*t);
Import this signal into SPTool and view the spectrum using various methods.
Time-Varying Spectra
The spectral estimation methods described so far are designed for the analysis of signals
with a constant spectrum over time. In order to nd time-varying spectra, dierent methods
of analysis and visualization must be used.
The time-dependent Fourier transform of a signal is a sequence of DFTs computed using a
sliding window. A spectrogram is a plot of its magnitude versus time.
[B f t] = specgram(x,nfft,fs,window,numoverlap)
calculates the time-dependent Fourier transform for the signal in vector x and returns the
DFT values B, the frequency vectors f, and the time vectors t. The spectrogram is computed
as follows:
1. The signal is split into overlapping sections and applies to the window specied by the
window parameter to each section.
2. It computes the discrete-time Fourier transform of each section with a length nfft
FFT to produce an estimate of the short-term frequency content of the signal; these
transforms make up the columns of B. The quantity length(window) numoverlap
species by how many samples specgram shifts the window.
3. For real input, specgram truncates to the rst nfft/2 + 1 points for nfft even and
(nfft + 1)/2 for nfft odd.
When called with no outputs, specgram displays the spectrogram.
Try:
Time-constant spectrum
t = 0:1/100:10-1/100;
x = sin(2*pi*15*t) + sin(2*pi*30*t);
specgram(x,256,100,hann(21),15)
colorbar
Time-varying spectrum
load handel
sound(y,Fs)
specgram(y,512,Fs,kaiser(100,5),75)
colorbar
Spectrogram Demos
specgramdemo
xpsound
Example: Reduced Sampling Rate
This example compares the sound and spectrogram of a speech signal sampled at progres-
sively reduced rates.
If you resample a signal at a fraction of the original sampling frequency, part of the signals
original frequency content is lost. The down-sampled signal will contain only those frequen-
cies less than the new Nyquist frequency. As down-sampling continues, the words in the
signal remain recognizable long after the original spectrogram has become obscured. This is
a tribute to the human auditory system, and is the basis of signal compression algorithms
used in communications.
Try:
edit HAL9000
HAL9000
Wavelets
One of the drawbacks of the Fourier transform is that it captures frequency information
about a signal without any reference to time. For stationary signals this is unimportant, but
for time-varying or bursty signals, time can be critical to an analysis.
The time-dependent Fourier transform computed by the specgram function is one solution
to this problem. By applying a DFT to a sliding window in the time domain, specgram
captures a signals frequency content at dierent times. The disadvantage of this method
is that it is uniform on all time intervals: it does not adjust to local idiosyncrasies in the
frequency content. As a result, more subtle nonstationary characteristics of a signal can go
undetected.
Wavelet analysis uses a more adaptable method, and is capable of revealing trends, break-
down points, discontinuities in higher derivatives, and self-similarity that the DFT might
miss.
A wavelet is a waveform of eectively limited duration that has an average value of zero.
The discrete wavelet transform (DWT) computes coecients of similarity between a signal
and a sliding wavelet. The coecients are found with wavelets of dierent scales (widths
that approximate dierent frequencies) to analyze the signal at dierent resolutions. In a
wavelet analysis, a signal is iteratively decomposed into the sum of a lowpass approximation
and a progressive sequence of highpass details.
The Wavelet Toolbox adds wavelet analysis techniques to the signal processing techniques
available in the Signal Processing Toolbox.
wavemenu
brings up a menu for accessing graphical tools in the Wavelet Toolbox.
Try:
wavemenu
Select Wavelet 1-D
and then File Example Analysis Basic Signals Frequency breakdown
S is the signal
a
5
is the approximation
d
n
are the details
What is happening in this signal and how does the wavelet analysis show it?
(The material in this lab handout was put together by Paul Beliveau and derives principally from
the MathWorks training document MATLAB for Signal Processing, 2006.)
c 2006GM
E E 2 7 5 Lab June 30, 2006
Lab 3. LTI Systems, the Z-Transform, and an Introduc-
tion to Filtering
Linear Time Invariant Systems
x[n] h[n] y[n]
A system is:
linear if y[N] is a linear combination of values of x[n] and y[n] for n N . A dierence
equation expressing this relation must not include constants or nonlinear functions of
x and y.
time-invariant if x[nN] produces output y[nN] for any N. That is, the system re-
sponse does not change over time. Dierence equation coecients must not be explicit
functions of n.
For LTI systems, inputs can be decomposed into linear combinations of simpler signals,
responses to individual inputs can be analyzed individually, and the total response can be
found by superposition.
An arbitrary LTI system can be completely described by its impulse response. The impulse
response h[n] is the response of the system to a unit impulse at n = 0. In Matlab, vectors
subscripts start at 1, so we will dene the impulse response as the response of the system to
a unit impulse at n = 1. By superposition, the response of the system to an arbitrary input
x[n] can be described as a linear combination of scaled and shifted impulse responses, giving
rise to the convolution sum.
y[n] =

k=
x[k]h[n k] = x[n] h[n]
Try a few simple convolutions:
h = [1 2 3]; % impulse response of the filter
stem(h)
c 2006GM
x=1; % input is an impulse
y=conv(x,h);
figure; stem(y) % output is the impulse response
x=[1 1 1];
y=conv(x,h);
figure; stem(y)
x=[1 2 3];
y=conv(x,h);
figure; stem(y)
LTI System Representation: Dierence Equations
Matlabs Signal Processing Toolbox provides several models for representing linear, time-
invariant systems. Dierence equations describe the input/output behavior of an LTI system
directly in terms of signal values.
N

k=0
a
k
y[n k] =
M

m=0
b
m
x[n m]
y[n] =
M

m=0
b
m
x[n m]
N

k=1
a
k
y[n k]
Note the summation limits in the two equations.
A dierence equation can be described in Matlab as two vectors:
b = [b0 b1 ... bM]; a = [a0 a1 ... aN];
When a is nonzero (so that y[n] depends on previous values of y), the system is said to be
recursive. It will have an innite impulse response (IIR). When a is zero, the system is said
to be nonrecursive. It will have a nite impulse response (FIR).
What does a non-zero a imply in terms of the connections in a lter block dia-
gram (where the blocks represent delays)?
Example:
Represent the following dierence equation as two vectors:
y[n] + 0.2y[n 2] = x[n] + 2x[n 1]
b = [1 2 0];
a = [1 0 0.2];
Why is the rightmost zero in the expression for b necessary?
The z-Transform
Just as the Fourier transform forms the basis of signal analysis, the z-transform forms the
basis of system analysis. If x[n] is a discrete signal, its z-transform X(z) is given by:
X(z) =

n=
x[n]z
n
The z-transform maps a signal in the time domain to a power series in the complex (fre-
quency) domain: x[n] X(z).
There are many advantages to working with z-transformed signals:
linearity and superposition are preserved
x[n k] z
k
X(z)
x[n] X(1/z)
a
n
x[n] X(z/a)
x[n] y[n] X(z)Y (z)
The overall result is that the algebra of system analysis becomes greatly simplied in the
z domain. The only tradeo is the necessity of taking an inverse transform to obtain time
domain responses.
Since the response y[n] of an LTI system to input x[n] is given by the convolution x[n] h[n],
where h[n] is the impulse reponse, we have
y[n] = x[n] h[n] Y (z) = X(z)H(z)
The ratio H(z) = Y (z)/X(z) denes the impulse response (and so the system response),
and is called the transfer function of the system.
LTI System Representation: Transfer Functions
The z-transform transforms a dierence equation into a transfer function. The transfer
function can be written either in discrete lter form:
H(z) =
b
0
+ b
1
z
1
+ b
2
z
2
+ ... + b
M
z
M
a
0
+ a
1
z
1
+ a
2
z
2
+ ... + a
N
z
N
or, by multiplying the numerator and denominator by the highest power of z, in proper form:
H(z) =
b
0
z
M
+ b
1
z
M1
+ b
2
z
M2
+ ... + b
M
a
0
z
N
+ a
1
z
N1
+ a
2
z
N2
+ ... + a
N
Either form can be represented in Matlab by a vector of coecients for the numerator and
denominator:
b = [b0 b1 ... bM]; a = [a0,a1 ... aN];
y[n] + 0.2y[n 2] = x[n] + 2x[n 1] Original dierence equation
Y (z) + 0.2z
2
Y (z) = X(z) + 2z
1
X(z) z-transform
H(z) = Y (z)/X(z) =
1 + 2z
1
1 + 0.2z
2
Discrete lter form
=
z
2
+ 2z
z
2
+ 0.2
Proper form
b = [1 2 0]; Matlab representation
a = [1 0 0.2];
Try:
b = [1 2];
a = [1 0 0.2];
[beq aeq] = eqtflength(b,a)
LTI System Representation: Zero-Pole-Gain
If the numerator and denominator of the proper form of a transfer function are factored, the
zeros and poles (i.e., the zeros of the denominator) become apparent:
H(z) = k
(z q
0
)(z q
1
)...(z q
N1
)
(z p
0
)(z p
1
)...(z p
N1
)
The leading coecient in the numerator, k, is called the gain.
Example:
H(z) =
z
2
+ 2z
z
2
+ 0.2
Zeros:
z
2
+ 2z = 0
z(z + 2) = 0
z = 0 and z = 2
Poles:
z
2
+ 0.2 = 0
z =

0.2j
Gain:
k = 1
The location of the zeros and poles of the transfer function determines the response of an
LTI system.
Matlabs Signal Processing Toolbox provides a number of functions to assist in the zero-
pole-gain analysis of a system.
[z p k] = tf2zpk(b,a)
nds the zeros z, poles p, and gain k from the coecients b and a of a transfer function in
discrete lter form.
[z p k] = tf2zp(b,a)
nds the zeros z, poles p, and gain k from the coecients b and a of a transfer function in
proper form.
There is no dierence between tf2zpk and tf2zp if the lengths of the lter coecient vectors
are rst equalized using eqtength.
zplane(z,p)
zplane(b,a)
both display the zeros and poles of a system. A o marker is used for zeros and an x marker
is used for poles. The unit circle is also plotted for reference during stability and phase
analysis.
Try:
b=[1 2 0];
a=[1 0 0.2];
[z p k] = tf2zpk(b,a)
zplane(z,p)
Explain the display
Zero-Pole Placement in Filter Design
LTI systems, particularly digital lters, are often designed by positioning zeros and poles in
the z-plane. The strategy is to identify passband and stopband frequencies on the unit circle
and then position zeros and poles by considering the following.
1. Conjugate symmetry
All poles and zeros must be paired with their complex conjugates.
2. Causality
To ensure that the system does not depend on future values, the number of zeros must
be less than or equal to the number of poles.
3. Origin
Poles and zeros at the origin do not aect the magnitude response.
4. Stability
For a stable system, poles must be inside the unit circle. Pole radius is proportional to
the gain and inversely proportional to the bandwidth. Passbands should contain poles
near the unit circle for larger gains.
5. Minimum phase
Zeros can be placed anywhere in the z-plane. Zeros inside the unit circle ensure min-
imum phase. Zeros on the unit circle give a null response. Stopbands should contain
zeros on or near the unit circle.
6. Transition band
A steep transition from passband to stopband can be achieved when stopband zeros
are paired with poles along (or near) the same radial line and close to the unit circle.
7. Zero-pole interaction
Zeros and poles interact to produce a composite response that might not match design
goals. Poles closer to the unit circle or farther from one another produce smaller
interactions. Zeros and poles might have to be repositioned or added, leading to a
higher lter order.
Zero-Pole-Gain Editing in SPTool
Run:
sptool
To access the Pole/Zero Editor in SPTool, do the following:
1. Click the New button under the Filters list in SPTool.
2. Select the Pole/Zero Editor in the Algorithm list.
3. View system characteristics as you position poles and zeros.
(Well see this tool again later in the lab.)
Linear System Transformations
The Signal Processing Toolbox provides a number of functions for converting among system
representations.
Note: Representation conversions can produce systems with slightly dierent characteristics.
This dierence is due to roundo error in the oating point computations performed during
conversion.
Transfer State Zero Partial Lattice Second Convolution
Function Space Pole Fraction Filter Order Matrix
Gain Sections
Transfer tf2ss tf2zp residuez tf2latc tf2sos convmtx
Function tf2zpk
roots
State ss2tf ss2zp ss2sos
Space
Zero-Pole- zp2tf zp2ss zp2sos
Gain poly
Partial residuez
Fraction
Lattice latc2tf
Filter
Second sos2tf sos2ss sos2zp
Order
Sections
Try:
b = [1 2 0];
a = [1 0 0.2];
[A B C D] = tf2ss(b,a)
Can you explain what A, B, C, and D are?
Impulse Reponse
The impulse response h[n] and its z-transform (the transfer function H(z)) completely char-
acterize the response of an LTI system. For input x[n] in the time domain (X(z) in the
frequency domain), the output of the system y[n] in the time domain (Y (z) in the frequency
domain) is given by:
y[n] = x[n] h[n] (convolution) Time domain
Y (z) = X(z)Y (z) (product) Frequency domain
The Signal Processing Toolbox function
[h t]=impz(b,a,n,fs)
computes the impulse response of the LTI system with transfer function coecients b and a.
It computes n samples and produces a vector t of length n so that the samples are spaced
1/fs units apart. It returns the response in the column vector h and sample times in the
column vector t. When called with no outputs, it plots the response.
For a system identication application, the impulse response of an unknown system can be
compared with the impulse response of a model of that system, and model parameters (such
as zeros and poles) can be tuned to match the response of the unknown system.
Try:
b=[1 2 0];
a=[1 0 0.2];
impz(b,a,10,1e3)
Frequency Response
The Signal Processing Toolbox function
freqz(b,a)
when called with no output arguments, plots the magnitude and unwrapped phase of the
lter in the current gure window.
Try:
b=[1 2 0];
a=[1 0 0.2];
freqz(b,a)
The following form of the function
[h w]=freqz(b,a)
computes the frequency response of the LTI system with transfer function coecients b and
a. It returns the frequency response vector h and the corresponding angular frequency vector
w. The vector w has values ranging from 0 to the Nyquist rate, which is normalized to
radians per sample by default. The response is calculate using a default of 512 samples.
Try:
[h w]=freqz(b,a);
subplot(211), plot(w/pi, 20*log10(abs(h)))
subplot(212), plot(w/pi, (180/pi)*angle(h))
h=freqz(b,a,w)
returns the frequency response vector h calculated at the frequencies (in radians per sample)
supplied by the vector w.
[h f]=freqz(b,a,l,fs)
In this syntax, the frequency response is calculated using a sampling frequency specied by
the scalar fs in Hz. The frequency vector f is calculated in Hz and has values ranging from
0 to fs/2 Hz.
Frequency Response and the Transfer Function
A z-plane plot of the magnitude of the transfer function H(z) has a height of zero at each
of the zeros and a singularity at each of the poles. The curve on this surface above the unit
circle gives the frequency response.
H(z) = 8
z 1
z
2
1.2z + 0.72
You can take a look at the function:
edit transferplot
Run it:
transferplot
Then try this, to see a birds-eye view:
view(0,90)
Filter Visualization Tool
For an arbitrary LTI system, the Filter Visualization Tool (fvtool) displays:
Magnitude response
Phase response
Group delay
Impulse response
Step response
Pole-zero plot
Filter coecients
You can:
Click the plot to display a value at a point
Change axis units by right-clicking an axis label or by right-clicking the plot and selecting
Analysis Parameters
Export the display to a le with Export on the File menu
Try this:
a=[1 0 .2];
b=[1 2 0];
fvtool(b,a)
Change the magnitude plot to dB vs. log(f).
Filtering a Signal
LTI systems are commonly called lters, and the process of generating the output y[n] from
an input x[n] is called ltering. To lter a signal using a system described by transfer func-
tion coecients b and a, use the Matlab lter function.
y=filter(b,a,x)
lters the data in vector x with the lter described by numerator coecient vector b and
denominator coecient vector a. If a(1) is not equal to 1, filter normalizes the lter
coecients by a(1). If a(1) equals 0, filter returns an error.
The filter function is implemented in a direct form II transposed lter architecture.
This is the dierence equation
y[n] = b(1)x[n]+b(2)x[n1]+...+b(nb+1)x[nnb]...a(2)y[n1]...a(na+1)y[nna]
where n1 is the lter order (the highest degree in the proper form of the transfer function).
Use what is in the noisyC script to generate a noisy sine wave:
fs = 1e4;
t = 0:1/fs:5;
sw = sin(2*pi*262.62*t); % Middle C
n = 0.1*randn(size(sw));
swn = sw + n;
Use a simple lowpass (averaging) lter:
b=[.25 .25 .25 .25];
a=[1 0 0 0];
y=filter(b,a,swn);
figure, plot(t,y), axis([0 0.04 -1.1 1.1])
h=impz(b,a);
y2=conv(swn,h);
figure, plot(t,y2(1:end-3)), axis([0 0.04 -1.1 1.1])
How do the two outputs (y and y2) compare?
How do the methods (lter and conv) dier?
Using SPTool
Choose File Import from the SPTool main menu.
Try importing the lter just created.
To apply a Filter in SPTool:
1. Select the signal to be ltered.
2. Select the lter to apply.
3. Click the Apply button under the Filters list.
Try ltering the noisy middle C signal swn with the simple lowpass lter created earlier.
Exercises:
1. Plot the frequency responses of the two lters with the following dierence equations.
Sampling frequency: 2kHz.
Low-pass: y[n] = 0.5x[n] + 0.5[n 1] (averaging)
High-pass: y[n] = 0.5x[n] + 0.5[n 1] (nite dierencing)
2. Filter the signal x from Exercise 1 with each of the lters. (Run hilo to recreate the
signal.) View and listen to the outputs. Note that the two components of x are at 5% and
95% of the Nyquist frequency, respectively.
3. Open each lter in the Pole/Zero editor in SPTool. Adjust the locations of the poles and
zeros and observe the eects on both the response and the ltered signal.
Cepstral Analysis
Certain signals, such as speech signals, are naturally modeled as the output of an LTI system;
i.e., as the convolution of an input and an impulse response. To analyze such signals in terms
of system parameters, a deconvolution must be performed. Cepstral analysis is a common
technique for such deconvolution.
The technique is based on two facts: a convolution in the time domain becomes a product
in the z-domain, and logarithms of products become sums. If:
x[n] = x
1
[n] x
2
[n] X(z) = X
1
(z)X
2
(z)
then:

X(z) = log(X(z)) = log(X


1
(z)) + log(X
2
(z)) x[n] = x
1
[n] + x
2
[n]
The convolved signals become additive in the new cepstral domain. (The word cepstral
reverses the rst letters in the word spectral to reect the back-and-forth between the time
and frequency domains.)
The complex cepstrum x[n] of a sequence x[n] is calculated by nding the complex natural
logarithm of the Fourier transform of x, then the inverse Fourier transform of the resulting
sequence:
x[n] =
1
2

log[X(e
j
)]e
jn
d
The Signal Processing Toolbox function cceps perfoms this operation and the function icceps
performs the inverse.
The real cepstrum (or just the cepstrum) of x[n] is found as above, using only the magnitude
of the Fourier transform. It is computed by the Signal Processing Toolbox function rceps.
The original sequence cannot be reconstructed from only its real cepstrum, but you can
reconstruct a minimum-phase version of the sequence by applying a windowing function in
the cepstral domain. The minimum phase reconstruction is returned by rceps in a second
output argument.
Read the echodetect.m script (shown below), then try running it. (You might need to disable
the sound line.)
% ECHODETECT Demonstrates cepstral analysis for echo detection.
% Load stereo sound sample HGC and sample frequency fs:
load helloGC
% Delays for echoes (in samples):
d1 = 10000;
d2 = 20000;
d3 = 30000;
% Attenuation for echoes (percent):
a = 0.6;
% Add echoes to sound sample:
s0 = [HGC; zeros(d1+d2+d3,2)];
s1 = [zeros(d1,2); HGC; zeros(d2+d3,2)];
s2 = [zeros(d2,2); HGC; zeros(d1+d3,2)];
s3 = [zeros(d3,2); HGC; zeros(d1+d2,2)];
s = s0 + a*s1 + a
2
*s2 + a
3
*s3;
% Play sound with echoes:
%sound(s,fs)
% Cepstral analysis.
% Plot cepstrum of sound with echoes (2nd channel) in red:
c = cceps(s(:,2));
plot(c,r)
hold on
% Overlay cepstrum of original sound (2nd channel) in blue:
c0 = cceps(s0(:,2));
plot(c0,b)
axis([0 1e5 -1 1])
xlabel(Sample Number)
ylabel(Complex Cepstrum)
title([Echoes at ,num2str(d1), ,num2str(d2), ,num2str(d3)])
% Note red peaks at delays.
(The material in this lab handout was put together by Paul Beliveau and derives principally from
the MathWorks training document MATLAB for Signal Processing, 2006.)
c 2006GM
E E 2 7 5 Lab June 30, 2006
Lab 4. IIR Filters in Matlab
Filter Design
The goal of ltering is to perform frequency-dependent alteration of a signal. A simple design
specication for a lter might be to remove noise above a certain cuto frequency. A more
complete specication might call for a specic amount of passband ripple (Rp, in decibels),
stopband attenuation (Rs, in decibels), or transition width (Wp - Ws, in hertz). A precise
specication might ask to achieve the performance goals with the minimum lter order, call
for an arbitrary magnitude response, or require an FIR lter.
IIR lter design methods dier primarily in how performance is specied. For loosely spec-
ied requirements, as in the rst case described previously, a Butterworth lter is often
sucient. More rigorous lter requirements can be met with Chebyshev and elliptic lters.
The Signal Processing Toolbox order selection functions estimate the minimum lter order
that meets a given set of requirements. To meet specications with more rigid constraints,
such as linear phase or arbitrary response, it is best to use direct IIR methods such as the
Yule-Walker method or FIR methods.
Filter Congurations
First, recall that when dealing with sampled signals, we can normalize the frequencies to
the Nyquist frequeny, which is half the sampling frequency. All the lter design functions
in the Signal Processing Toolbox operate with normalized frequencies, so that they do not
require the system sampling rate as an extra input argument. The normalized frequency is
always in the interval 0 f 1. For example, with a 1000 Hz sampling frequency, 300 Hz
is 300/500 = 0.6. To convert normalized frequency to angular frequency around the unit
circle, multiply by . To convert normalized frequency back to Hertz, multiply by half the
sample frequency.
Lowpass lters remove high frequencies (near 1)
Highpass lters remove low frequencies (near 0)
Bandpass lters pass a specied range of frequencies
Bandstop lters remove a specied range of frequencies
c 2006GM
Calculate a normalizing factor:
fs = 1e4;
f = 400;
nf = 400/(fs/2)
Filter Specications in Matlab
Wp - Passband cuto frequencies (normalized)
Ws - Stopband cuto frequencies (normalized)
Rp - Passband ripple: deviation from maximum gain (dB) in the passband
Rs - Stopband attenuation: deviation from 0 gain (dB) in the stopband
The Filter Design and Analysis Tool (FDATool) shows these specications graphically:
fdatool
The order of the lter will increase with more stringent specications: decreases in Rp, Rs,
or the width of the transition band.
IIR Filter Design
The primary advantage of IIR lters over FIR lters is that they typically meet a given set
of specications with a much lower lter order than a corresponding FIR lter.
Although IIR lters have nonlinear phase, data processing in Matlab is commonly performed
o-line, that is, the entire data sequence is available prior to ltering. This allows for
a noncausal, zero-phase ltering approach (via the ltlt funtion), which eliminates the
nonlinear phase distortion of an IIR lter.
The classical IIR lters - Butterworth, Chebyshev Types I and II, elliptic, and Bessel - all
approximate the ideal brick wall lter in dierent ways. The Signal Processing Toolbox
provides functions to create all these types of IIR lters in both the analog and digital
domains (except Bessel, for which only the analog case is supported), and in lowpass, high-
pass, bandpass, and bandstop congurations. For most lter types, you can also nd the
lowest lter order that ts a given lter specication in terms of passband ripple, stopband
attenuation, and the transition band widths.
Try the following:
doc filtfilt
Use what is in the noisyC script to generate a noisy sine wave:
fs = 1e4;
t = 0:1/fs:5;
sw = sin(2*pi*262.62*t);
n = 0.1*randn(size(sw));
swn = sw + n;
Create a Butterworth lter of order 2 with a cuto at 400 Hz:
[b a] = butter(2, 400/(fs/2));
Note the nonlinear phase:
figure, freqz(b,a)
Now create a lter with lter:
y = filter(b,a,swn);
figure, plot(t,y), axis([0 0.04 -1.1 1.1]), title(Using filter())
soundsc(y,1e4)
Filter with filtfilt:
y2=filtfilt(b,a,swn);
figure, plot(t,y2), axis([0 0.04 -1.1 1.1]), title(Using filtfilt())
soundsc(y2,1e4)
IIR Filter Types
Butterworth lter
Provides the best Taylor series approximation to the ideal lowpass lter response at
analog frequencies = 0 and = ; for any order n, the magnitude squared response
has 2n 1 zero derivatives (that is, it is maximally at) at these locations. Response
is monotonic overall, decreasing smoothly from = 0 to = .
Chebyshev Type I lter
Minimizes the absolute dierence between the ideal and the actual frequency response
over the entire passband by using an equal ripple in the passband. Stopband response
is maximally at. The transition from passband to stopband is more rapid than for
the Butterworth lter.
Chebyshev Type II lter
Minimizes the absolute dierence between the ideal and the actual frequency response
over the entire stopband by using an equal ripple in the stopband. Passband response
is maximally at. The stopband does not approach zero as quickly as the type I lter
(and does not approach zero at all for even-valued lter order n). The absence of ripple
in the passband, however, is often an important advantage.
Elliptic lter
Equiripple in both the passband and stopband. Generally meets lter requirements
with the lowest order of any supported lter type. Given a lter order n, passband
ripple, and stopband ripple, elliptic lters minimize transition width.
Bessel lter
Analog lowpass lters have maximally at group delay at zero frequency and retain
nearly constant group delay across the entire passband. Filtered signals therefore
maintain their waveform in the passband. Digital Bessel lters, however, do not have
this maximally at property, and are not supported by Matlab. Generally require a
higher lter order than other lters for satisfactory stopband attenuation.
Analog Prototyping
The principal design technique for digital IIR lters supported by the Signal Processing Tool-
box is based on the conversion of classical lowpass analog lters to their digital equivalents.
The technique involves three steps:
1. Find an analog lowpass lter with cuto frequency of 1 and translate this prototype
lter to the desired band conguration.
2. Transform the lter to the digital domain.
3. Discretize the lter.
The toolbox provides functions for each of these steps:
Design Task Available Low-Level Functions
Analog lowpass prototype buttap, cheb1ap, besselap,
ellipap, cheb2ap
Frequency transformation lp2lp, lp2hp, lp2bp, lp2bs
Discretization bilinear, impinvar
Alternatively, the butter, cheby1, cheby2, ellip, and besself functions perform all steps of the
lter design and the buttord, cheb1ord, cheb2ord, and ellipord functions perform minimum
order computations for IIR lters. These functions are sucient for many design problems,
and the lower level functions are generally not needed. If you do have an application where
you need to transform the band edges of an analog lter, or discretize a rational transfer
function, the low-level functions allow you to do so.
Example: Bandpass Filter
To demonstrate, we will use various methods to design a bandpass lter that passes middle
C at 262.62 Hz. The lter has the following specications:
Order:
n 10
Sampling frequency:
fs = 10, 000Hz
Normalized passband cuto frequencies:
Wp = [150 350]/(fs/2) = [0.03 0.07]
Normalized stopband cuto frequencies:
Ws = [100 400]/(fs/2) = [0.02 0.08]
Passband ripple:
Rp = 0.5dB
Stopband attenuation:
Rs = 20dB
Butterworth Method: Analog Prototype
For the Butterworth method, we will follow the three steps of analog prototyping at a low
level.
1. Lowpass analog prototype
[z p k] = buttap(5);
Outputs z, p, and k contain the zeros, poles, and gain of a lowpass analog lter of
order 5 with a cuto frequency of 1 rad/s. The bandpass lter will have order 10 (2
cutos).
2. Frequency Transformation
Use the lp2bp function to transform the lowpass prototype to a bandpass analog lter.
First, convert to state-space form so the lp2bp function can accept it:
[A B C D] = zp2ss(z,p,k);
Now, nd the bandwidth and center frequency, and call lp2bp:
u1 = 0.03*2*pi;
u2 = 0.07*2*pi;
Bw = u2-u1;
Wo = sqrt(u1*u2); % Center frequency
[At Bt Ct Dt] = lp2bp(A,B,C,D,Wo,Bw);
Finally, calcualte the frequency response and plot its magnitude:
[b a] = ss2tf(At,Bt,Ct,Dt);
w = linspace(0.01,1,500)*2*pi;
h = freqs(b,a,w);
semilogy(w/2/pi,abs(h))
grid on
xlabel(Normalized Frequency);
ylabel(Analog Response)
Explain the function of each line of code in this section individually.
Butterworth Method: Discretization
3. Discretization
Impulse invariance
The impinvar function creates a digital lter whose impulse response is sampled from
the analog impulse response.
[bz1 az1] = impinvar(b,a,fs);
returns transfer function coecients bz1 and az1 of the digital lter whose impulse
response is equal to the impulse response of the analog lter with transfer function
coecients b and a, using a sampling frequency of fs. There should be negligible
frequency content above fs/2, since high frequency content would be aliased into lower
bands when sampling. The impinvar function works for some lowpass and bandpass
lters, but it is not appropriate for highpass and bandstop lters.
Bilinear transformation
The bilinear transformation is a nonlinear mapping of the continuous s-domain to the
discrete z-domain given by z = (k +s)/(k s). The transfer function H(s) of the ideal
analog lter is mapped to the transfer function H(z) of a corresponding discrete lter.
[bz2 az2] = bilinear(b,a,fs);
returns transfer function coecients bz2 and az2 of the digital lter that is the bilinear
transformation of the analog lter with transfer function coecients b and a, using a
sampling frequency of fs. By default, the frequency warping constant k is set equal to
twice the sampling frequency. Band edges can vary slightly from the specied cutos
because of the nonlinear nature of the transformation.
Omitted the following:
Chebyshev Type I Method
Elliptic Method
Direct IIR Design
Direct design methods nd a lter based on specications in the discrete domain. Unlike the
analog prototyping method, direct designs are not constrained to the standard lowpass, high-
pass, bandpass, or bandstop congurations. Filters with an arbitrary, perhaps multiband,
frequency response are possible.
The yulewalk function designs IIR digital lters by tting a specied frequency response. It
nds the inverse FFT of the ideal desired power spectrum and solves modied Yule-Walker
equations using the resulting autocorrelation function samples. The statement
[b a] = yulewalk(n,f,m)
returns vectors b and a containing the n + 1 numerator and denominator coecients of
the order n IIR lter whose frequency-magnitude characteristics approximate those given in
vectors f and m. f is a vector of frequency points ranging from 0 to 1, where 1 represents the
Nyquist frequency. m is a vector containing the desired magnitude response at the points
in f. f and m can describe any peicewise linear magnitude response, including a multiband
response.
Note that yulewalk does not accept phase information, and no statements are made about
the optimality of the resulting lter.
Example: Arbitrary Response IIR Filter
Problem
Design a 12th-order bandstop lter tting the following frequency response data:
f = [0 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.6 1];
m = [1 1 0.5 0.5 0 0 0.5 0.5 1 1];
Solution
Compute the Yule-Walker t and frequency response:
[b a] = yulewalk(12,f,m);
[h w] = freqz(b,a,128);
Overplot ideal and designed responses:
plot(f,m,r--,w/pi,abs(h),b-)
legend(Ideal,Yule-Walker Design)
title(Comparison of Response Magnitudes)
Try:
edit directstop
directstop(10)
directstop(20)
directstop(30)
Exercise
1. Create a 3-second signal containing the sum of three tones of equal amplitude, each en-
tering with 1-second delays. The signal should
Have a sampling frequency of 8192 Hz
Contain a 220 Hz tone for 0 < t < 3
Contain a 300 Hz tone for 1 < t < 3
Contain a 440 Hz tone for 2 < t < 3
View the signal before proceeding.
Now create a noise signal to add to the tone signal.
n = randn(size(t));
Create the sum of the tone and the noise.
y = x + n;
2. Design an arbitrary response IIR lter to remove the 300 Hz component from the three-
tone signal with white noise y.
3. Plot the designed response and a Yule-Walker t together.
4. Filter the signal y with the designed lter.
5. Compare signals and spectra before and after ltering.
Filter Design with SPTool
The Filter Designer in the SPTool allows you to design and edit IIR and FIR lters of
various lengths and types, with lowpass, highpass, bandpass, and bandstop, and multiband
congurations.
To activate the Filter Designer, click either the New button or the Edit button under the
Filters list box in SPTool.
Try:
sptool
Filter Design with FDATool
The Filter Design Toolbox works with Matlab and the Signal Processing Toolbox to pro-
vide a complete environment for start-to-nish lter design. Its graphical user interface, the
FDATool, supports many advanced techniques not available in SPTool.
Use the FDATool to:
Design lters
Quantize lters
Analyze lters
Modify existing lter designs
Realize Simulink models of quantized direct form FIR lters
Perform digital frequency transformations of lters
Try:
fdatool
Filter Analysis with FDATool
The Filter Visualization Tool (FVTool) can be accessed from within the FDATool by choos-
ing the Full View Analysis option in the Analysis menu or by clicking the Full View
Analysis button on the toolbar.
The FVTool is dynamically linked to the FDATool, so changes to a lter design automatically
update plotted responses for analysis.
Importing Existing Filters
The FDATool can be used to edit and analyze existing lters by importing them from the
Matlab workspace. To do so:
1. Select Import Mode.
2. Choose the desired Filter Structure.
3. Enter the coecients.
4. Enter the Sampling Frequency.
5. Click Import Filter.
Exporting from the FDATool
Filters designed in the FDATool can be exported to
The Matlab Workspace
(lter coecients can be vectors or objects)
The SPTool
(for capabilities not available in FDATool, such as spectral analysis)
MAT-les
Text les
C header les
To export a lter, choose File Export in the FDATool.
(The material in this lab handout was put together by Paul Beliveau and derives principally from
the MathWorks training document MATLAB for Signal Processing, 2006.)
c 2006GM
E E 2 7 5 Lab June 30, 2006
FIR Filters in Matlab
Lab 5. FIR Filter Design in Matlab
Digital lters with nite-duration impulse reponse (all-zero, or FIR lters) have both advan-
tages and disadvantages when compared to innite-duration impulse response (IIR) lters.
FIR lters have the following primary advantages:
They can have exactly linear phase.
They are always stable, even when quantized.
The design methods are generally linear.
They can be realized eciently in hardware.
The lter startup transients have nite duration.
The primary disadvantage of FIR lters is that they often require a much higher lter order
than IIR lters to achieve a given level of performance. Correspondingly, the delay of these
lters is often much greater than for an equal performance IIR lter.
FIR Methods
The Signal Processing Toolbox supports a variety of methods for the design of FIR lters.
FilterMethod Description FilterFunctions
Windowing Apply window to truncated inverse r1, r2, kaiserord
Fourier transform of desired lter
Multiband with Equiripple or least squares approach rls, rpm, rpmord
Transition Bands over frequency subbands
Constrained Least Minimize squared integral error over rcls, rcls1
Squares entire frequency range subject to maximum
error constraints
Arbitrary Response Arbitrary responses, including nonlinear crpm
phase and complex lters
Raised Cosine Lowpass response with smooth, rrcos
sinusoidal transition
c 2006GM
Impulse Response Revisited
FIR lters are described by dierence equations of the form
y(n) =
M

m=0
b
m
x(n m)
where the ltered signal y(n) is just a linear combination of current and previous values
of the input signal x(n). The coecients b are the numerator coecients of the transfer
function. The denominator of the transfer function will always be a = 1. The order of the
lter is n = length(b) 1.
If the input signal is the unit impulse x = [1 0 0 0 ...], then the corresponding impulse response
y(n) = h(n) is identical to b(n):
h(0) = b
0
x(0) = b
0
h(1) = b
0
x(1) + b
1
x(0) = b
1
h(2) = b
0
x(2) + b
1
x(1) + b
2
x(0) = b
2
...etc.
The FIR lter coecients give the impulse response.
Try this:
b = [-1 0 2 -3 1]; % no need to specify the a coefficients
stem(b)
figure, impz(b,1)
Why are the x-axis scales dierent?
Linear Phase Filters
A lter whose impulse response is symmetric about its midpoint is called a (generalized)
linear phase lter. For such lters,
The DFT of the impulse response will be either purely real or purely imaginary.
The magnitude of the DFT is scaled by the lters magnitude response (there is no ampli-
tude distortion).
The phase shift of a ltered signal will vary linearly with frequency (pure time delay
with no phase distortion).
The phase delay ()/ and group delay d()/d() will be equal and constant. For
an order n linear phase FIR lter, the phase delay and group delay is n/2.
The absence of either amplitude distortion or phase distortion preserves the waveform of
signals in the passband.
Except for crpm, all the FIR lter design functions in the Signal Processing
Toolbox design linear phase lters only.
Try:
a = 1;
b = fir1(5,0.5);
fvtool(b,a)
Look at the phase delay and the group delay.
FIR Filter Types
The symmetric impulse response of a linear phase lter can have an odd or an even number
of points,and can have an odd or even symmetry about the midpoint, leading to four lter
types:
Type I: Odd length, even symmetry
Type II: Even length, even symmetry
Type III: Odd length, odd symmetry
Type IV: Even length, odd symmetry
Depending on the lter type, certain restrictions apply:
Filter Filter Symmetry ResponseH(0) ResponseH(1)
Type Order (Nyquist)
Type I Even b(k) = b(n + 2 k), k = 1, ..., n + 1 No restriction No restriction
Type II Odd b(k) = b(n + 2 k), k = 1, ..., n + 1 No restriction H(1) = 0
Type III Even b(k) = b(n + 2 k), k = 1, ..., n + 1 H(0) = 0 H(1) = 0
Type IV Odd b(k) = b(n + 2 k), k = 1, ..., n + 1 H(0) = 0 No restriction
The functions r1, r2, rls, rpm, rcls, rcls1, and rrcos all design type I and II linear
phase FIR lters by default. Both rls and rpm design type III and IV linear phase FIR
lters given a hilbert or dierentiator ag. The function crpm can design any type of
linear or nonlinear phase lter.
Because the frequency response of a type II lter is zero at the Nyquist frequency (high
frequency), r1 does not design type II highpass and bandstop lters. For odd-valued n in
these cases, r1 adds 1 to the order and returns a type I lter.
Window-Based Design
Windowing is a common design method for FIR lters. In this method,
The ideal frequency response H(f) is sampled.
The corresponding ideal impulse response h(n) is determined by the inverse Fourier trans-
form. In general, this response cannot be implemented in a digital lter because it is innite
and noncausal.
h(n) is symmetrically truncated (multiplied by a nite, symmetric window) to create a
linear phase nite impulse response.
The approximation to the ideal lter is best in a mean square sense, compared to other
approximations of the same length, by Parsevals theorem. However, the abrupt truncation
leads to overshoot (Gibbs phenomenon) and ripples in the spectrum. The undesirable eects
of truncation are reduced or eliminated by the use of tapered windows.
Windowing does not explicitly impose amplitude response constraints, such as passband
ripple or stopband attenuation. It must be used iteratively to produce designs that meet
such specications.
Try:
edit windemo
windemo(20)
windemo(50)
windemo(100)
What do the arguments (20, 50, 100) specify?
How does the lter change with the argument?
Windowing Functions
The Signal Processing Toolbox supports a variety of windows commonly used in FIR lter
design. Typing
help window
provides a list of available functions:
bartlett Bartlett window
barthannwin Modied Bartlett-Hanning window
blackman Blackman window
blackmanharris Minimum 4-term Blackman-Harris window
bohmanwin Bohman window
chebwin Chebyshev window
flattopwin Flat Top window
gausswin Gaussian window
hamming Hamming window
hann Hann window
kaiser Kaiser window
nuttallwin Nuttall dened minimum 4-term Blackman-Harris window
parzenwin Parzen (de la Valle-Poussin) window
rectwin Rectangular window
triang Triangular window
tukeywin Tukey window
Individual functions take inputs for a window length n and window parameters and return
the window w in a column vector of length n. (Note: Use w for array products with row vec-
tor impulse responses.) The window function serves as a gateway to the individual functions.
w = gausswin(64,alpha)
and
w = window(@gausswin,64,alpha)
both return a Gaussian window of length 64 with standard deviation equal to 1/alpha.
Try:
help window
n=15;
w=gausswin(n,3);
stem(-7:7,w)
n=linspace(0,6*pi,100);
y=sinc(n);
figure, stem(n,y)
W=gausswin(2*length(y),3);
w=W(length(y)+1:end);
wy=w.*y;
figure, stem(n,wy,m)
Explain the y and wy plots.
Windowing and Spectra
When a signal is truncated, high-frequency components are introduced that are visible in
the DFT. By windowing the truncated signal in the time domain, endpoints are assigned a
reduced weight. The eect on the DFT is to reduce the height of the side lobes, but increase
the width of the main lobe.
Try:
edit windft
windft
Tuncated signal and DFT:
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
1
0.5
0
0.5
1
Truncated Signal
0 1 2 3 4 5 6 7 8 9 10
0
10
20
30
40
50
DFT of Truncated Signal
M
a
g
n
i
t
u
d
e
Tuncated, windowed signal and DFT:
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
1
0.5
0
0.5
1
Truncated, Windowed Signal
0 1 2 3 4 5 6 7 8 9 10
0
5
10
15
20
25
DFT of Truncated, Windowed Signal
M
a
g
n
i
t
u
d
e
Window Visualization Tool
The transition bandwidth of a window-based FIR lter is determined by the width of the
main lobe of the DFT of the window function, adjustable by changing the lter order.
Passband and stopband ripples are determined by the magnitude of the side lobe of the DFT
of the window function, and are usually not adjustable by changing the lter order.
The actual approximation error is scaled by the amount of the passband magnitude response.
Ideally, the spectrum of a window should approximate an impulse. The main lobe should be
as narrow as possible and the side lobes should contain as little energy as possible.
The Window Visualization Tool (WVTool) allows you to investigate the tradeos among
dierent windows and lter orders.
wvtool(windowname(n))
opens WVTool with time and frequency domain plots of the n-length window specied in
windowname, which can be any window in the Signal Processing Toolbox. Several windows
can be given as input arguments for comparative display.
Try:
wvtool(hamming(32),kaiser(32,2.5),flattopwin(32))
wvtool(kaiser(32,1),kaiser(32,5),kaiser(32,10))
Window Design and Analysis Tool
The Window Design and Analysis Tool (WinTool) is used in conjunction with the Window
Visualization Tool.
Use WVTool for displaying and comparing existing windows created in the Matlab workspace.
Use WinTool to interactively design windows with certain specications and export them
to the Matlab workspace.
Most window types satisfy some optimality criterion. Some windows are combinations of
simpler windows. For example, the Hann window is the sum of a rectangular and a cosine
window, and the Bartlett window is the convolution of two rectangular windows. Other
windows emphasize certain desirable features. The Hann window improves high-frequency
decay (at the expense of larger peaks in the side lobes). The Hamming window minimizes
side lobe peaks (at the expense of slower high-frequency decay). The Kaiser window has
a parameter that can be tuned to control side lobe levels. Other windows are based on
simple mathematical formulas for easy application. The Hann window is easy to use as a
convolution in the frequency domain.
An optimal time-limited window maximizes energy in its spectrum over a given frequency
band. In the discrete domain, the Kaiser window gives the best approximation to such an
optimal window.
wintool
opens WinTool with a default 64-point Hamming window. Try it - experiment with dierent
window designs and export them to the workspace.
Comment on the Chebyshev compared to the Blackman-Harris window.
Can you think of an advantage one would have over the other?
Example: Lowpass Filter
Consider the ideal, or brick wall, digital low-pass lter with a cuto frequency of
0
rad/s.
This lter has magnitude 1 at all frequencies less than
0
, and magnitude 0 at frequencies
between
0
and . Its impulse response sequence h(n) is
1
2

H()e
jn
d =
1
2

0
e
jn
d =

0

sinc

This lter is not implementable since its impulse response is innite and noncausal. To
create a nite-duration impulse response, turncate it by applying a window. Retain the
central section of impulse response in the turncation to obtain a linear phase FIR lter. For
example, a length 51 lter with a lowpass cuto frequency
0
of 0.4 rad/s is
b=0.4*sinc(0.4*(-25:25));
The window applied here is a simple rectangular window. By Parsevals theorem, this is
the length 51 lter that best approximates the ideal lowpass lter, in the integrated least
squares sense. To display the lters frequency response in FVTool, type
fvtool(b,1)
Ringing and ripples occur in the response, especially near the band edge. This Gibbs ef-
fect does not vanish as the lter length increases, but a nonrectangular window reduces its
magnitude. Multiplication by a window in the time domain causes a convolution or smooth-
ing in the frequency domain. Apply a length 51 Hamming window to the lter and display
the result using FVTool:
bw=b.*hamming(51);
fvtool(b,1)
Using a Hamming window greatly reduces the ringing. This is at the expense of transition
width (the windowed version takes longer to ramp from passband to stopband) and optimal-
ity (the windowed version does not minimize the integrated least squared error).
Try:
b=0.4*sinc(0.4*(-25:25));
fvtool(b,1)
bw=b.*hamming(51);
fvtool(bw,1)
Right-click the y-axis label in FVTool and choose Magnitude squared on both plots.
Where in the plot is the ringing reduced by the window?
Standard Band FIR Design
The Signal Processing Toolbox functions r1 and r2 are both based on the windowing
method. Given a lter order and a description of an ideal lter, these functions return a
windowed inverse Fourier transform of the ideal lter. Both use Hamming windows by de-
fault, but they accept any windowing function.
r1 resembles the IIR lter design functions in that it is formulated to design lters in stan-
dard band congurations: lowpass, bandpass, highpass, and bandstop. The commands
n=50;
Wn=0.4;
b=fir1(n,Wn);
create a row vector b containing the coecients of the order n Hamming-windowed lter.
This is a lowpass, linear phase FIR lter with cuto frequency Wn. Wn is a number between
0 and 1, where 1 corresponds to the Nyquist frequency, half the sampling frequency.
For a highpass lter, simply append the string high to the functions parameter list. For
a bandpass or bandstop lter, specify Wn as a two-element vector containing the passband
edge frequencies; append the string stop for the bandstop conguration.
b=fir1(n,Wn,window);
uses the window specied in column vector window for the design. The vector window must
be n + 1 elements long. If you do not specify a window, r1 applies a Hamming window.
The kaiserord function estimates the lter order, cuto frequency, and Kaiser window pa-
rameter needed to meet a given set of specications. Given a vector of frequency band edges,
a vector of magnitude, and a maximum allowable ripple, kaiserord returns appropriate input
parameters for the r1 function.
Try:
edit fir1demo
fir1demo
Exercise
1. Design a windowed FIR bandstop lter to remove the 300 Hz component from the three-
tone signal with noise y from Lab IIR Filters in Matlab. Use a sampling frequency of
8192 Hz.
2. Plot the response.
3. Filter the signal y with the designed lter.
4. Compare signals and spectra before and after ltering.
Arbitrary Response FIR Filters
The r2 function also designs windowed FIR lters, but with an arbitrarily shaped piecewise
linear frequency response. (The IIR counterpart of this function is yulewalk).
b=fir2(n,f,m);
returns row vector b containing the n+1 coecients of an order n FIR lter. The frequency-
magnitude characteristics of this lter match those given by vectors f and m.
b=fir2(n,f,m,window);
uses the window specied in column vector window for the design. The vector window must
be n + 1 elements long. If you do not specify a window, r2 applies a Hamming window.
The function crpm is used to design complex and nonlinear-phase equiripple FIR lters. It
allows arbitrary frequency-domain constraints.
Try:
edit directstop2
directstop2(10)
directstop2(100)
directstop2(500)
edit nlinphase
nlinphase
Multiband Filters
The function rls designs linear-phase FIR lters that minimize the weighted, integrated
squared error between an ideal piecewise linear function and the magnitude response of the
lter over a set of desired frequency bands.
b=firls(n,f,a)
returns row vector b containing the n+1 coecients of the order n FIR lter whose frequency-
amplitude characteristics approximately match those given by vectors f and a.
The function rls allows you to introduce constraints by dening upper and lower bounds
for the frequency response in each band.
The function rcls1 is used specically to design lowpass and highpass linear phase FIR
lters using constrained least squares.
Try:
edit firlsdemo
firlsdemo
edit firclsdemo
firclsdemo
Raised Cosine Filters
The sinc function, which is the impulse response of an ideal lowpass lter, forms the basis
for several other interpolating functions of the form
h(n) = f(n)sinc

n
n
s

, where f(0) = 1
One commonly-used form is the raised cosine function:
h
rc
(n) =
cos(R
n
ns
)
1 (2R
n
ns
)
2
sinc

n
n
s

, 0 R 1
R is called the rollo factor. Like the sinc function, the raised cosine function is 1 at n = 0
and 0 at all other sampling instances n = n
s
. In contrast to the sinc function, the raised
cosine has faster decaying oscillations on either side of the origin for R > 0. This results in
improved reconstruction if samples are not acquired at exactly the sampling instants (i.e., if
there is jitter). It also uses fewer past and future values in the reconstruction, as compared
to the sinc function. The shape of the functions spectrum is the raised cosine.
The ideal raised cosine lowpass lter frequency response consists of unity gain at low fre-
quencies, a raised cosine function in the middle, and total attenuation at high frequencies.
The width of the transition band is determined by the rollo factor.
b=firrcos(n,F0,df,fs)
b=firrcos(n,F0,df,fs,bandwidth)
are equivalent, and return an order n lowpass linear-phase FIR lter with a raised cosine
transition band. The cuto frequency is F0, the transition bandwidth df, and sampling
frequency is fs, all in hertz. df must be small enough so that F0 df/2 is between 0 and
fs/2. b is normalized so that the nominal passband gain is always equal to 1.
b=firrcos(n,F0,r,fs,rolloff)
interprets the third argument, r, as the rollo factor instead of the transition bandwidth,
df. r must be in the range [0, 1].
Try:
b = firrcos(20,0.25,0.25,2);
freqz(b)
Describe what you see.
Frequency Domain Filtering
Often, a long (perhaps continuous) stream of data must be processed by a system with only
a nite length buer for storage. The data must be processed in pieces, and the processed
result constructed from the processed pieces.
In the overlap-add method, an input signal x(n) is partitioned into equal length data blocks.
The lter coecients (impulse response) and each block of data are transformed to the fre-
quency domain using the FFT, where they can be eciently convolved using multiplication.
The partial convolutions of the signal are returned to the time domain with the IFFT, where
they are shifted and summed using superposition.
tlt implements the overlap-add method for FIR lters.
y=fftfilt(b,x)
uses an FFT length of nt = 2
nextpow2(n)
and a data block length of nt-length (b)+1 (ensures
circular convolution).
rlt incurs an oine startup cost when converting the coecients b to the frequency
domain. After that, the number of multiplications tlt performs relative to lter (which
implements the lter in direct form) is log
2
(L)/N, where L is the block length and N is the
lter length. (Multiplications are a good measure of performance, since they are typically
expensive on hardware.) The net result is that for lters of high order, tlt outperforms
lter.
Try:
x=[1 2 3 4 5 6];
h=[1 1 1];
y=conv(h,x)
x1=[1 2 3];
x2=[4 5 6];
y1=conv(h,x1)
y2=conv(h,x2)
Y1=[y1, zeros(1,3)];
Y2=[zeros(1,3),y2];
Y=Y1+Y2
Describe what is happening in this code.
The following script takes a few moments to run.
edit filttimes
filttimes
Above what order can you say that tlt is always faster?
(The material in this lab was put together by Paul Beliveau and handout derives principally from
the MathWorks training document MATLAB for Signal Processing, 2006.)
c 2006GM
E E 2 7 5 Lab June 30, 2006
Lab 6. Advanced Filter Design in Matlab
Introduction
This lab will briey describe the following topics:
Median Filtering
Advanced IIR Filter Design
Advanced FIR Filter Design
Adaptive Filters
Multirate Filters
Median Filtering
Filitering using LTI systems is limited to designs that compute outputs from linear combi-
nations of current and previous values of the inputs and the outputs. Sometimes, however,
linear techniques are insucient to perform the required ltering.
A simple example of a nonlinear ltering technique is median ltering. The Signal Process-
ing Toolbox function medfilt1 implements one-dimensional median ltering by applying a
sliding window to a sequence. The lter replaces the center value in the window with the
median value of all the points within the window.
y = medfilt1(x,n)
applies an order n (window length n) one-dimensional median lter to vector x. The function
considers the signal to be 0 beyond the endpoints. The output y has the same length as x.
y = medfilt1(x,n,blksz)
uses a for loop to compute blksz (block size) output samples at a time. Use blksz <<
length(x) if you are low on memory, since medfilt uses a working matrix of size n blksize.
By default, blksz = length(x) for fastest execution with sucient memory.
Median lters are often used for noise reduction. The advantage of median lters over linear
lters such as averaging lters comes from the robustness of the median with respect to
outliers. Outlying data has much less eect on the center of a data set when the center is
measured by the median rather than the mean. As a result, median lters are useful for
removing salt and pepper noise involving extreme outliers while otherwise preserving the
shape of the signal.
c 2006GM
A two-dimensional median ltering function, medfilt2, is available in the Image Processing
Toolbox.
Try:
x = [1 2 3 4 5];
y = medfilt1(x,1)
y = medfilt1(x,2)
y = medfilt1(x,3)
edit saltysig
saltysig(5)
saltysig(10)
saltysig(20)
Advanced IIR Designs
The Filter Design Toolbox includes three functions for the design of IIR lters that optimally
meet lter requirements.
iirlpnorm
uses a least-p
th
norm unconstrained optimization algorithm for IIR lters that have arbitrary
shape magnitude response curves. The algorithm diers from the traditional IIR design
algorithms in several respects:
The designs are done directly in the z-domain.
There is no need for bilinear transformation.
The numerator and the denominator order can be dierent.
You can design IIR lters with arbitrary magnitude response in addition to the basic
lowpass, highpass, bandpass, and bandstop.
iirlpnormc
uses a least-p
th
norm optimization algorithm as well, but this version is constrained to let
you restrict the radius of the poles of the IIR lter.
iirgrpdelay
uses a least-p
th
constrained optimization algorithm to let you design allpass IIR lters that
meet a prescribed group delay specication.
The Demos section of the documentation for the Filter Design Toolbox includes examples
for each of the functions:
Least P-Norm Optimal IIR Filter Design
Constrained Least P-Norm IIR Filter Design
IIR Filter Design Given a Prescribed Group Delay
Try the demos on IIR lter design in the documentation for the Filter Design Toolbox.
Advanced FIR Designs
The Filter Design Toolbox also includes a function for the design of FIR lters that optimally
meet lter requirements.
firgr
provides a minimax, or equiripple algorithm that allows you to design the following real FIR
lters:
Types 1 through 4 linear phase
Minimum phase
Maximum phase
Minimum order, even or odd
Extra-ripple
Maximal-ripple
Constrained-ripple
Single-point band
Forced gain
Arbitrarily shaped frequency response
The Demos section of the documentation for the Filter Design Toolbox includes the follow-
ing examples:
Minimax FIR Filter design
Least Pth-Norm optimal FIR Filter Design
FIR Nyquist (Lth Band) Filter Design
Constrained Equiripple FIR Filter Design
Constrained-Band Equiripple FIR Filter Design
Ecient Narrow Transition Band FIR FIlter Design
Halfband FIR Filter Design
Try the demos on FIR lter design in the documentation for the Filter Design Toolbox.
Adaptive Filters
Adaptive lters are self-learning systems. As an input signal enters the lter, the coecients
adjust themselves to achieve a desired result. The result might be
System identication
Identify the response of an unknown system such as a communications channel or a telephone
line. The lter adapts once, then stays xed.
Inverse system identication
Develop a lter with a responsse that is the inverse of an unknown system. You can overcome
echoes in modem connections and local telephone lines by inserting an inverse adaptive lter
and using it to compensate for the induced noise on the lines.
Noise cancellation
Perform active noise cancellation where the lter adapts in real time to keep the error small.
Compare this to system identication.
Prediction
Predict a signals future values.
Adaptive Filters: Block Diagram
The block diagram below represents a general adaptive lter.
An adaptive FIR lter designs itself based on the characteristics of the input sinal and a
signal that represents the desired behavior of the lter on the input. The lter does not
require any other frequency response specications. The lter uses an adaptive algorithm
to reduce the error between the output signal y(n) and the desired signal d(n). When
perormance criteria for e(n) have achieved their minimum values through the iterations of
the adapting algorithm, the adaptive lter is nished and its coecients have converged to
a solution.
The output from the adaptive lter should approximate the desired signal d(n). If the char-
acteristics of the input (the lter environment) are changed, the lter adapts by generating
a new set of coecients.
Adaptive lter functions in the Filter Design Toolbox implement the largest block in the
gure, using an appropriate technique for the adaptive algorithm. Inputs are x(n) and
initial values for a and b.
Choosing an Adaptive Filter
Two main considerations are involved in choosing an adaptive lter: the job to do and the
lter algorithm to use.
The suitability of an adaptive lter design is determined by
Filter Consistency
Does lter performance degrade when the coecients change slightly as a result of quan-
tization or the use of xed-point arithmetic? Will excessive noise in the signal hurt the
performance of the lter?
Filter Performance
Does the lter provide sucient identication accuracy or delity, or does it provide su-
cient signal discrimination or noise cancellation?
Tools
Do tools exist to make the lter development process easier? Better tools can make it prac-
tical to use more complex adaptive algorithms.
DSP Requirements
Can the lter perform its job within the constraints of the application? Does the proces-
sor have sucient memory, throughput, and time to use the proposed adaptive ltering
approach? Can you use more memory to reduce the throughput, or use a faster signal
processor?
Simulating lters using the functions in the Filter Design Toolbox is a good way to investigate
these issues.
Beginning with a least mean squares (LMS) lter, which is relatively easy to implement,
might provide sucient information for your evaluation. This can also form a basis from
which you can study and compare more complex adaptive lters. At some point, you must
test your design with real data and evaluate its performance.
Adaptive Filters in the Filter Design Toolbox
Adaptive lters are implemented in the Filter Design Toolbox as adaptive lter (adaptlt)
objects. This object-oriented approach to adaptive ltering involves two steps:
1. Use a lter constructor method to create the lter.
2. Use the lter method associated with adaptlt objects to apply the lter to data. The
lter method for adaptlt objects takes precedence over the lter function in Matlab
when input arguments involve adaptlt objects.
There are over two dozen adaptive lter constructor methods in the Filter Design Toolbox.
They fall into the following ve categories:
Least mean squares (LMS) based FIR adaptive lters
Recursive least squares (RLS) based FIR adaptive lters
Ane projection (AP) FIR adaptive lters
FIR adaptive lters in the frequency domain (FD)
Lattice based (L) FIR adaptive lters
For example,
ha = adaptfilt.lms(length,step,leakage,coeffs,states);
constructs an FIR LMS adaptive lter object ha. The input arguments for each constuctor
method are described in the documentation.
To apply the lter to a signal x, use
y = filter(ha,x)
Note that in the context of adaptive ltering, Kalman lters are equivalent to RLS lters.
Other nonadaptive Kalman lters are available in the Control System Toolbox.
Try:
edit afodemo
afodemo
System Identication
One common application of adaptive lters is to identify an unknown black box system.
Applications are as diverse as nding the response of an unknown communications channel
and nding the frequency response of an auditorium to design for echo cancellation.
In a system identication application, the unknown system is placed in parallel with the
adaptive lter.
In this case the same input x(n) feeds both the adaptive lter and the unkown system. When
e(n) is small, the adaptive lter response is close to the response of the unknown system.
Try:
edit filterid
filterid(1e2,0.5)
filterid(5e2,0.5)
filterid(1e3,0.5)
filterid(5e2,0.1)
filterid(5e2,0.5)
filterid(5e2,1)
Sketch the block diagram of an adaptive lter system to be used for system
identication.
Inverse System Identication
By placing the unknown system in series with an adaptive lter, the lter becomes the inverse
of the unknown system when e(n) becomes small. The process requires a delay inserted in
the desired signal d(n) path to keep the data at the summation synchronized and the system
causal.
Without the delay element, the adapting algorithm tries to match the output y(n) from the
adaptive lter to an input x(n) that has not yet reached the adaptive elements because it
has to pass through the unknown system. Including a delay equal to the delay caused by
the unknown system prevents this condition.
Plain old telephone systems (POTS) commonly use inverse system identication to compen-
sate for the copper transmission medium. When you send data or voice over telephone lines,
the losses due to capacitances distributed along the wires behave like a lter that rolls o
at higher frequencies (or data rates). Adding an adaptive lter with a response that is the
inverse of the wire response, and adapting in real time, compensates for the rollo and other
anomalies, increasing the available frequency range and data rate for the telephone system.
Sketch the block diagram of an adaptive lter system to be used for inverse
system identication.
Noise Cancellation
In noise cancellation, adaptive lters remove noise from a signal in real time. To do this, a
signal Z(n) correlated to the noise is fed to the adaptive lter.
As long as the input to the lter is correlated to the unwanted noise accompanying the
desired signal, the adaptive lter adjusts its coecients to reduce the value of the dierence
between y(n) and d(n), removing the noise and resulting in a clean signal in e(n). Notice
that the error signal converges to the input data signal in this case, rather than converging
to zero.
Try:
edit babybeat
babybeat
Sketch the block diagram of an adaptive lter system to be used for system
identication.
Prediction
Predicting signals might seem to be an impossible task. Some limiting assumptions must
be imposed by assuming that the signal isperiodic and either steady or slowly varying over
time.
Accepting these assumptions, an adaptive lter attempts to predict future values of the
desired signal based on past values. The signal s(n) is delayed to create x(n), the input to
the adaptive lter. s(n) also drives the d(n) input. When s(n) is periodic and the lter is
long enough to remember previous values, this structure, with the delay in the input signal,
can perform the prediction.
You might use this structure to remove a periodic component from stochastic noise signals.
Sketch the block diagram of an adaptive lter system to be used for system
identication.
Multirate Filters
Multirate lters alter the sample rate of the input signal during the ltering process. They
are useful in both rate conversion and lter bank applications.
Like adaptive lters, multirate lters are implemented in the Filter Design Toolbox as mul-
tirate lter (mlt) objects. Again, this object-oriented approach to ltering involves two
steps:
1. Use a lter constructor method to create the lter.
2. Use the lter method associated with mlt objects to apply the lter to data. The
lter method for mlt objects (and all lter objects) takes precedence over the lter
function in Matlab when input arguments involve mlt objects.
There are approximately a dozen multirate lter constructor methods in the Filter Design
Toolbox.
For example,
hm = mfilt.firdecim(3)
creates an FIR decimator with a decimation factor of 3. The only input argument needed
is the decimation factor. Input arguments for each constructor method are described in the
documentation.
To apply the lter to a signal x, use
y = filter(hm,x)
Multirate lters can also be designed interactively in the FDATool. Click the sidebar button
Create a Multirate Filter.
Try:
edit multidemo
multidemo
Interactively design the lter in the demo in the FDATool.
(The material in this lab handout was put together by Paul Beliveau and derives principally from
the MathWorks training document MATLAB for Signal Processing, 2006.)
c 2006GM
E E 2 7 5 Lab June 30, 2006
Lab 7. Filter Implementation in Matlab
Introduction
This lab examines the process of moving from lter design to hardware implementation.
The lab investigates various architectures and various quantization schemes, and discusses
hardware description language (HDL) code generation.
Filter Architectures
After the lter design process has generated lter coecients b and a, or a lter object
h (such as adaptlt or mlt object), the lter is implemented in a lter architecture using
low-level operations of sum, gain, and delay (essentially, a block diagram of the dierence
equation).
Approximately two dozen lter architectures are supported by Matlabs Signal Processing
and Filter Design Toolboxes:
Direct-form I Lattice autoregressive (AR)
Direct-form I, second-order sections Lattice autoregressive
Direct-form I transposed moving average (ARMA)
Direct-form I transposed, Lattice moving-average (MA)
second-order sections for maximum phase
Direct-form II Lattice moving-average (MA)
Direct-form II, second-order sections for minimum phase
Direct-form II transposed, Coupled, allpass lattice
Direct-form II transposed, Coupled, allpass lattice
second-order sections with power complementary output
Direct-form FIR State-space
Direct-form symmetric FIR Scalar gain object
Direct-form antisymmetric FIR Filters arranged in series
Overlap-add FIR Filters arranged in parallel
Lattice allpass
c 2006GM
FilterStructure
The lter command, when given b and a coecient inputs, implements a direct-form II
transposed architecture. When lter is given object input, it implements an architecture
determined by the constructor used to create the object. The lter architecture of a lter
object is stored in its FilterStructure eld.
To create a lter object with a given architecture from lter coecients b and a, use the dlt
command. For example,
h = dfilt.df2t(b,a)
creates a direct-form II transposed discrete-time lter (dlt) object that implements the lter
with coecients b and a.
To display the FilterStructure eld of a lter object h, type:
get (h, FilterStructure)
FilterStructure is a read-only property. To use a dierent structure, construct a new lter
with the appropriate method (or, for quantized lters only, use convert to switch to a new
structure).
For a complete list of dlt constructors, and a list of associated methods for working with
lter objects, type:
help dfilt
Try:
help dfilt
hm = mfilt.firdecim(3)
get(hm, FilterStructure)
b = fir2(12,[0 0.4 0.5 1],[1 1 0 0]);
hd1 = dfilt.dffir(b)
hd2 = dfilt.fftfir(b)
isstable(hd1)
isstable(hd2)
Filter Architecture Reference
As a reference, the graphical user interface archref allows you to browse dierent architec-
tures, view a representative block diagram, and see the corresponding syntax for dlt when
creating a discrete-time lter object with the specied architecture in its FilterStructure
eld.
Try:
archref
Filter Realization
The Filter Design and Analysis tool allows you design a lter (or import one from the
Workspace) and then realize it in a Simulink block diagram with a specied architecture.
Choose File Import Filter from Workspace in FDATool or click the Import Filter
sidebar button to open the Import Filter panel. You can then enter the names of Workspace
variables for lter coecients and choose a lter architecture from the pop-up menu.
You can convert from one architecture to another within the FDATool by choosing Edit
Convert Structure.
To realize a lter, click the Realize Model sidebar button.
The generated Simulink subsystem block uses delay, gain, and sum blocks in xed-point
mode. (Requires Simulink Fixed Point to run.)
Try:
[b a] = butter(8,0.25);
fdatool
Import the lter into the FDATool with various architectures and then realize your design
in Simulink.
Test your realizations in the following model:
realmodel
Can you determine the frequencies of interest?
Is this model LP, BP, or HP?
Change the design of the lter by changing the order and the cuto frequencies and repeat
as needed.
Second-Order Sections
Second-order sections (SOS) are second-order factors of a transfer function H(z) with gain
g:
H(z) = g
N

k=1
H
k
(z) = g
N

k=1
b
0k
+ b
1k
z
1
+ b
2k
z
2
a
0k
+ a
1k
z
1
+ a
2k
z
2
When quantized, higher order lters suer from an accumulation of coecient errors. Filters
whose transfer functions have been factored into second-order sections are much more robust.
Sections can be combined in parallel or in cascade to create higher order lters.
Matlab represents the second-order sections form of a lter as an N x 6 array, where N is
the number of sections. Each row contains a single section, where the row elements are the
three numerator and three denominator coecients that describe the second-order section:
S =

b
01
b
11
b
21
a
01
a
11
a
21
b
02
b
12
b
22
a
02
a
12
a
22
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
b
0N
b
1N
b
2N
a
0N
a
1N
a
2N

[S g] = tf2sos(b,a)
returns a matrix S in second-order section form with gain g equivalent to the lter represented
by coecient vectors a and b.
hds = sos(hd)
returns a lter object hds in second-order sections with a direct-form II transposed structure.
On the View menu in both FDATool and FVTool there is an option for SOS View. When
you have an SOS lter in either tool, SOS View lets you see the performance of the sections
of the lter - individually, cumulatively, or overall.
Try:
[b a] = butter(8,0.25);
hd = dfilt.df1(b,a)
hd.Numerator
hd.Denominator
hds = sos(hd)
hds.sosMatrix
Import the lter into the FDATool in SOS form and view the individual, cumulative, and
overall performance of the sections.
How does the SOS version compare to the original version in terms of perfor-
mance?
Digital Signals
The value of a signal, at any instant, is its instantaneous amplitude. Time can assume con-
tinuous values t or discrete values n/f
s
, where f
s
is the sampling frequency. The amplitude
can also assume a continuum of values or be quantized to a nite number of discrete levels.
This results in four possible kinds of signals:
Analog: continuous time, continuous level
Quantized: continous time, discrete level
Sampled: discrete time, continuous level
Digital: discrete time, discrete level
Sampling and quantization form the critical link between analog and digital signals.
Quantization
Hardware implementations can require lters to use minimum power, generate minimum
heat, and avoid computational overload in their processors. Meeting these constraints often
requires the use of quantized lters.
Because of nite signal lengths and the nite memory of computer processors, only a nite
set of quantized sequences is possible. Sampling and quantization round or truncate signal
values within the nite set of possibilities. Quantized samples are represented by a group
(word) of zeros and ones (bits) that can be processed digitally. The ner the quantization,
the larger the number of bits in the sample word.
Like sampling, improper quantization leads to loss of information. Unlike sampling, however,
no matter how ne the quantization, the eects are irreversible, since word lengths must be
nite. Finite word lengths appear as nonlinear eects (such as overow and limit cycles) and
can make systematic treatment of quantization extremely dicult. Quantization noise can
be described in statistical terms, and is usually considered only in the nal stages of design.
The Filter Design Toolbox gives you a laboratory for experimenting with quantization eects
before a lter is implemented in hardware.
The toolbox includes tools to simulate the eects of quantization, and allows you to inves-
tigate the transition from oating-point to xed-point arithmetic and observe the eects on
performance. You can use the toolbox quantization functions for constructing, applying, and
analyzing quantizers, quantized lters, and quantized FFTs.
Fixed-Point Aritmetic
You specify how numbers are quantized using xed-point arithmetic. The two most impor-
tant parameters are:
Word length w in bits
Fraction length f in bits
The fraction length is the number of bits between the binary point and the least-signicant
bit.
Where you place the binary point determines how xed-point numbers are interpreted. For
example, for a signed (twos complement) xed-point number, 10.110 represents
2 + 2
1
+ 2
2
= 1.25.
A xed-point quantization scheme determines the dynamic range of the numbers that are
used. Numbers outside this range are always mapped to xed-point numbers within the
range when you quantize them. The precision is the distance between successive numbers
occurring within the dynamic range in a xed-point representation.
For a signed xed-point number with word length w and fraction length f, the dynamic
range is from 2
wf1
to 2
wf1
2
f
.
For an unsigned xed-point number with word length w and fraction length f, the dynamic
range is from 0 to 2
wf
2
f
.
In either case the precision is 2
f
.
When you quantize a number outside of the dynamic range, overows occur. Overows are
more frequent with xed-point quantization than with oating-point quantization, because
the dynamic range is less for equivalent word lengths. Overows can occur when you create a
xed-point quantized lter from an arbitrary oating-point design. You can either normalize
your coecients (and introduce a corresponding scaling factor for ltering) to avoid overows,
or else saturate or wrap.
Quantized Filters
The Filter Design Toolbox implements single-input-output lters as xed-point lters or as
single-precision or double-precision oating-point lters. Both single-precision oating-point
and xed-point lters are referred to as quantized lters.
To use the xed-point capabilities in the Filter Design Toolbox, either:
Use dlt or fdesign to create a lter object hd and set the Arithmetic property of the object
to single or xed:
set(hd,Arithmetic,fixed)
Copy an existing lter to inherit its properties.
Use the FDATool.
Fixed-point properties of a lter object hd become dynamically available when you set the
Arithmetic property to xed. To see the writable properties of hd, simply display the vari-
able in the Workspace. To see the complete list of properties, type
get(hd)
Use the set command (or index into the object structure array) to change properties such as
word length, fraction length, rounding, and overow handling. The documentation reference
Fixed Point Filter Properties gives a full description of lter properties and values.
When you apply a quantized lter to data, the lter coecients are quantized to your
specications, but so are the data that you lter (both the input and the output) and the
results of any arithmetic operations that occur during ltering.
Try:
[b a] = butter(8,0.25);
hd = dfilt.df1(b,a)
get(hd)
set(hd,Arithmetic,fixed)
get(hd)
set(hd,OverflowMode,Saturate)
get(hd)
d = fdesign.lowpass(n,fs);
set(d,Fcutoff,0.2)
designmethods(d)
d2 - butter(d)
fvtool(d)
edit qeffects
qeffects
Quantization in the FDATool
The Filter Design and Analysis Tool allows you to quantize lter designs and experiment
with xed-point properties to interactively evaluate performance tradeos in hardware.
In the FDATool, click the Set Quantization Parameters button and select a lter arith-
metic. Choosing xed-point arithmetic displays a tabbed panel with editable elds for each
of the quantization properties of the lter.
Try:
b = r1(101,0.45,low,kaiser(102,7.8573));
HDL Code Generation
The HDL Filter Designer Toolbox provides a development environment for application-
specic integrated circuit (ASIC) and eld programmable gate array (FPGA) designs. It will
automatically generate hardware description language (HDL) code based on lters designed
in the toolbox.
System designers and hardware developers use HDLs such as very high speed integrated
circuit (VHSIC) hardware denition language (VHDL), and Verilog to develop hardware
designs. HDLs provide a proven method for hardware design, but coding lter designs, and
hardware designs in general, is labor intensive and the use of these languages for algorithm
and system-level design is less than optimal.
Using the Filter Design HDL Coder, system architects and designers can spend more time
on ne-tuning algorithms and models through rapid prototyping and experimentation and
less time on HDL coding. Architects and designers can eciently design, analyze, simulate,
and transfer system designs to hardware developers.
For example, an architect or designer might use the Filter Design Toolbox, the Filter Design
and Analysis Tool, and the Filter Design HDL Coder to design a lter. Then, with the click
of a button, the Filter Design HDL Coder generates a VHDL or Verilog implementation of
the design and a corresponding test bench.
Generated code adheres to a clean HDL coding style that enables architects and designers
quickly to address customizations as needed. The test bench feature increases condence in
the correctness of the generated code and saves time spent on test bench implementation.
With the HDL Filter Designer Toolbox installed, choose Targets Generate HDL in
the FDATool.
(The material in this lab handout was put together by Paul Beliveau and derives principally from
the MathWorks training document Matlab for Signal Processing, 2006.)
c 2006GM
E E 2 7 5 Lab June 30, 2006
Lab 8. Signal Analysis Using Matlab Simulink
Introduction
The Matlab Simulink software allows you to model digital signals, examine power spectra
of digital signals, represent LTI systems in dierent formats, help turn specications for IIR
and FIR lters into working designs, and other operations.
This lab will briey describe how to use Matlabs Simulink software for signal analysis.
Computer Setup
You will need to make sure some examples and exercises are available on your computer
before beginning the lab.
1. Start Matlab.
2. Put the CD in the CD-ROM drive.
3. Set the Matlab current directory to the CD-ROM drive.
4. Run the Matlab install script install training on the CD. To do so, type the name at
the Matlab command prompt:
install training
5. The script should open a graphical user interface (GUI) that will guide you through
the installation procedure. In the GUI, you have these options:
Choose a class root directory for the les.
Choose the courses for which you want to install the les.
Add the course directory to your Matlab path and edit your startup.m le so that
the les are on the path each time you start Matlab.
The installation creates a subdirectory of your chosen root directory (the default is C:\class)
called courseles. This directory has subdirectories for each of the courses you install, labeled
by course number. These individual course directories contain the examples and exercises
for the courses. You may want to change the work directory to your M: drive and put it in
the path.
c 2006GM
Matlab Setup for Building Signal Processing Blockset Models
When you create a model using blocks from the Signal Processing Blockset, you may want
to adjust certain Simulink settings to reect the discrete time nature of a digital model.
The Signal Processing Blockset provides an M-le, dspstartup.m, that lets you automate this
conguration process so that every new model you create is precongured for simulating a
digital (discrete) system.
Statistical Signal Processing
Repeated observations (or simulations within the Simulink environment) of a random process
X under the same environmental conditions yield dierent results. The signal value of a
simulation, x(n), at sample n is not constant among the realizations in an ensemble; rather,
the ensemble is characterized by a set of probability density functions. Each individual signal
value x(n) of a specic realization in the ensemble can be thought of as the outcome of an
underlying random variable. The collection of these random variables, one for each sample
time, comprise the random process.
Working with random signals is easier when one or both of the following properties can be
shown to hold.
A signal is said to be stationary if the statistics over the simulation do not change with
a shift in time, i.e., if the random variables x(n) and x(n + N) have the same statistics for
every integer value of N.
A signal is said to be ergodic if the ensemble averages are equal to the time averages of
any sample function. In other words, the statistics for any given realization in the ensemble
are the same as the statistics for the ensemble.
Note that an ergodic signal must be stationary, but a stationary signal is not necessarily
ergodic.
Statistics
The Signal Processing Blockset has blocks to extract basic statistics from stochastic signals,
such as mean, median, variance, and correlation. These are the building blocks for much of
statistical signal processing.
Simple
Mean
x
= EX
Standard Deviation and Variance
2
x
= E{X
2
} E
2
{X}
Minimum and Maximum
Correlation
Autocorrelation and Cross-Correlation R
xy
() = E{X(t)Y

(t +)}
Trending
Detrend
Histogram
Sort
Example: Crosscorrelation
In a simple target ranging system, a transmitted signal x is compared with a received signal
y. y is modeled by the equation
y(n) = x(n d) +
where is an attenuation factor, d is a time delay, and is channel noise. If T is the return
time for the signal, then x and y should be correlated at n = T. The target will be located
at a distance of vT, where v is the channel speed of the signal.
Try:
multipathcorr
Example: Mean Block
The Mean block in the Signal Processing Blockset performs calculates the mean for a portion
of the input sequence. You can use this block with the Buer block as an averaging lter.
The Buer block generates a sliding window. The output buer size N indicates the length
of the window, while N M (where M is the buer ovelap), species the number of samples
the window slides at each time step.
The Mean block also has a running mean option that performs a cumulative muean calcula-
tion on the input sequence.
Try:
running mean
Example: Median Block
The Median block in the Signal Processing Blockset performs basic median operation on the
input sequence. You can use this block with the Buer Block as a median lter.
A median lter is a nonlinear ltering technique that uses a sliding window on a sequence.
The lter replaces the center value in the window with the median value of all the points
within the window.
The advantage of median lters over linear lters such as averaging lters comes from the
robustness of the median with respect to outliers. Outlying data has much less eect on the
center of a data set when the center is measured by the median rather than the mean. As
a result, median lters are useful for removing spike noise involving extreme outliers while
otherwise preserving the shape of the signal.
Try:
edit medianfilter
medianfilter
Discrete Fourier Transform (DFT)
The DFT of a real-valued N-point signal y is a complex-valued N-point conjugate-symmetric
signal Y , dened by the formula
Y (n) =
N1

k=0
y(k)e
j
2
N
kn
where e
j
2
N
are the complex N
th
roots of unity.
The points of the DFT correspond to the N discrete frequencies from 0 to 2, or the DC
frequency to the Sampling Frequency respectively.
Note
The DFT denes the discrete frequencies of a sampled periodic signal. The Discrete-Time
Fourier Transform (DTFT), on the other hand, denes all frequencies of a sampled aperiodic
signal.
Try:
fftgui
Drag the mouse to move some of the points in the real window and see how
the other windows change.
Fast Fourier Transform (FFT)
The FFT block in the Signal Processing Blockset uses an algorithm to calculate eciently
the DFT of an input signal. The algorithm requires that the input is frame-based with a
power-of-two column length.
The FFT operation requires approximately 2n
2
oating-point operations, where n is the
FFT length. Modern-day FFT algorithms have reduced the computational complexity from
n
2
to nlog
2
n. By restricting n to be a power of 2, an FFT of length n requires fewer than
3nlog
2
n oating-point operations using the new algorithms. For n = 2
20
or 1,048,576, the
calculation is faster by a factor of almost 35,000 times.
In this example, the Buer block sets the FFT window size by creating each windowed
signal as a frame-based input.
The FFT block returns a complex-valued sample-based signal containing the frequency
domain data.
The Vector Scope blocks are adjusted to display this frequency input.
The Matlab t function is based on FFTW, The Fastest Fourier Transform in the West,
developed by MIT graduate students Matteo Frigo and Steven G. Johnson. For information
about FFTW, including a C subroutine library, go to:
http://www.tw.org
Example: DFT
In this example, we use the FFT block to analyze signals in the frequency domain:
1. Open medianlter and running mean from previous examples.
2. Take the FFT of the signals before and after the ltering operations and use the Vector
Scope block to observe the signals in the frequency domain.
3. Set the input domain of the vector scope to Frequency Sample time of the original
time series to the proper rate.
4. Insert a Complex to Magnitude block before the Vector Scope block.
5. Use the IFFT block to view the original signal.
Try:
fft running mean
fft median
Use the following blocks to perform the frequency analysis:
Buer, FFT, Complex to Magnitude-Angle, Freq, IFFT, Time
FFT demos:
sigdemo1
phone
Aliasing
Sampling an analog signal in the time domain has the eect of producing spectral copies at
multiples of the sampling frequency. When the sampling frequency is less than the signal
bandwidth, aliasing will occur.
The example t aliasing illustrates a 5Hz sine wave sampled at 15Hz and the same 5Hz
signal sampled at 7.5Hz. In the rst case, the original 5Hz signal is reconstructed without
aliasing while in the second case, the 5Hz signal is aliased to 2.5Hz.
Try:
fftaliasing
Additional Transforms
One of the drawbacks of the Fourier transform is that time information is lost when obtaining
the frequency content. This is trivial for stationary signals since the signals statistics do not
change with shifts in time, but for time-varying or bursty signals, the time information
may be important to the user.
The Short-Time FFT block is one solution to this problem. By applying the FFT to a sliding
window in the time domain, time is preserved by taking snapshots of the FFT spectrum
throughout the simulation. The disadvantage of this method is that it is uniform on all time
intervals and is not robust to the local idiosyncrasies in the frequency content. As a result,
some nonstationary characteristics of a signal can go undetected.
Wavelet analysis uses a more adaptable method, and is capable of revealing trends, break-
down points, and discontinuities in higher derivatives that Fourier analysis might be unable
to capture. A wavelet is a waveform of eectively limited duration that has an average value
of zero.
Wavelet analysis uses lters to separate the signal into its low and high frequency content.
These signal components are manipulated with the sliding wavelet to produce the wavelet
coecients of similarity.
The Discrete Wavelet Transform (DWT) block decomposes the signal into a combination
of the approximation and detail coecients, which describe the relation of low and high
frequency respectively with the wavelet.
Try:
dspxfrm3
(The material in this lab handout was put together by Paul Beliveau and derives principally from
the MathWorks training document Simulink for Signal Processing, 2006.)
c 2006GM
E E 2 7 5 Lab July 12, 2006
Linear Predictive Coding for Speech Processing
Introduction
Some signals can be compressed and recovered using a form of autoregressive ltering known
as linear predictive coding (LPC). This lab will examine the LPC model.
Autoregressive models use past behavior of a process to predict its future behavior. The
most basic model uses just one sample of past behavior, AR(1):
f(n) =
1
f(n 1) + n(n)
where n(n) is Gaussian white noise. (This is also known as a Markov process.)
Higher-order models are extensions of the rst-order model. Here is AR(2):
f(n) =
1
f(n 1) +
2
f(n 2) + n(n)
Here is AR(p):
f(n) =
1
f(n 1) +
2
f(n 2) + . . . +
p
f(n p) + n(n)
LPC10 (p = 10) is often used for speech processing.
Matlab Simulink LPC Demo
In this lab, youll be using Microsoft Windows-specic tools for getting a signal into and out
of Matlab.
(If you know that the microphone and speakers are working on your system, you can skip
ahead to Microphone and Speakers in Simulink, below.)
c 2006GM
Test the Microphone and Speakers
Start and set up the Sound Recorder utility:
Start / Accessories / Entertainment / Sound Recorder
Edit/Audio Properties
Under Sound Recording, click the Volume button.
Maximize the volume under Microphone.
Check the Select box under Microphone.
Exit the Recording Control dialog box.
Try recording some speech with the Sound Recorder:
Click on the red circle to start recording.
Click on the black rectangle to stop.
Play back the sound. (You might have to adjust the speaker volume, either in the system
volume controls or on the speakers themselves, in order to hear the sound.)
Adjust the volume setting on the microphone as required and try again until you get a
clean recording.
Microphone and Speakers in Simulink
Start Matlab, then start Simulink by typing:
simulink
The Simulink Library Browser will come up.
Select from the pulldown menus:
File / New / Model
Get the necessary Simulink blocks:
Signal Processing Blockset / Platform Specic I/O / Windows (Win32)
Find the From Wave Device block and drag it to the new model window.
Find the To Wave Device block and drag it to the new model window.
Test the Simulink blocks:
Connect the two blocks with the mouse by left-clicking on one port and dragging to the
other port.
Menu pulldown: Simulation / Conguration Parameters
Set Start Time to 0.0 and Stop Time to 5.0, then click OK.
With the speakers facing away from the microphone to avoid feedback, start the simulation
from the Simulation pulldown menu. Speak into the microphone and you should hear the
output from the speakers.
Note that in Simulink you can also use a recorded wave le as an input (From Wave File),
and you can use a wave le recorder to capture output (To Wave File).
Start the LPC Demo
Find the LPC demo description under Matlab Help:
Demos / Blocksets / Signal Processing / Audio Processing / LPC analysis and synthesis
Click on dsplpc win32.mdl
or
In the main Matlab window, type:
dsplpc win32
Run the simulation to see that it works, then copy all the blocks except the source to the new
model window that you created earlier. You can draw a box around the blocks you want,
copy to the clipboard with control-c, then paste into the new model window with control-v.
In the new model window, replace the input block with a From Wave Device block and make
sure it is connected to the rest of the model. Delete the unused blocks (except Info).
Close the original model and dont save changes to it.
Double-click on the From Wave Device block and, in the parameters panel, change the sam-
ples per frame value to 80 (i.e., the value that the original source block had). You should
see the following values:
Sample rate: 8000 Hz
Sample width: 16 bits
Samples per frame: 80
Close the From Wave Device panel and go to the Simulation / Conguration Parameters
menu choice. Set the Start time to 0.0 and the Stop time to a few seconds.
Run the simulation and speak into the microphone.
Is the quality the same as what you heard with no processing?
Are there any dierences in the output due to the processing?
How is it if you whistle or sing?
How can you modify the model to verify that it is performing the processing that it claims
to perform?
(The material in this lab handout was put together by Paul Beliveau and derives principally from
the MathWorks training document Simulink for Signal Processing, 2006.)
c 2006GM
E E 2 8 9 Lab Fall 2006
LAB 1. INTRODUCTION TO C6713 DSK, CCS, SIMULINK
& IMPLEMENTATION
A PC is required to run Code Composer Studio which is required to compile and download
code to (run on) the DSP.
Figure 1: Typical lab setup
0.1 DSP Board Highlights
Texas Instruments TMS320C6713 DSP operating at 225 MHz
An AIC23 stereo codec
8 MB of synchronous DRAM
512 KB of non-volatile Flash memory
c 2006SG
Figure 2: C6713 DSK block diagram
4 user accessible LEDs and DIP switches
Congurable boot options
Standard expansion connectors for daughter card use
JTAG emulation through on-board JTAG emulator with USB host interface or external
emulator
Single voltage power supply (+5V)
0.2 Functional Overview of DSP Board
The DSP on the 6713 DSK interfaces to on-board peripherals through a 32-bit wide EMIF
(External Memory Interface). The SDRAM, Flash and CPLD are all connected to the bus.
ii
EMIF signals are also used for daughter cards. The DSP interfaces to analog audio signals
through an on-board AIC23 codec and four 3.5 mm audio jacks (microphone input, line
input, line output, and headphone output). The codec can select the microphone or the line
input as the active input. The analog output is sent to both the line out and headphone out
connectors. The line out has a xed gain, while the headphone out allows for an adjustable
gain. connectors.
A programmable logic device called a CPLD (Complex Programmable Logic Device)is
used to implement logic that ties the board components together. The DSK includes 4 LEDs
and a 4 position DIP switch which allow for interactive feedback.
Simulink communicates with Code Composer Studio through Real-Time Workshop.Code
Composer Studio communicates with the DSK through an embedded JTAG emulator with
a USB host interface. Matlab communicates with CCS via Link for Code composer Studio.
The DSK can also be used with an external emulator through the external JTAG connector.
Figure 3: Real-Time Workshop
iii
0.3 Basic Operation of the Board
1. Connect the included power supply to the DSK.
2. Connect the DSK to your PC with the USB cable.
3. Launch Matlab.
0.4 Simulink, Real-Time Workshop, Embedded Target for TI C6000 DSP and
Link for Code Composer Studio: An Overview
This section describes how to use Simulink, Real-Time Workshop, Embedded Target for TI
C6000 DSP and Link for CCS with CCS. Simulink uses a block based approach to algorithm
design and implementation. Real-Time Workshop converts these Simulink models into ANSI
C/C++ code that can be compiled using CCS. The Embedded Target for TI C6000 DSP
provides the APIs required by Real-Time Workshop to generate code specically for the
C6000 platform. Link for CCS is used to invoke the code building process from within CCS
to build an executable. This code can then be downloaded on the target DSP from where
it runs. The data on the target is accessible in CCS or in Matlab via Link for CCS or via
Real-Time Data Transfer (RTDX). This thesis primarily uses RTDX for accessing data on
the target DSP.
0.4.1 Initial Configuration
To verify that CCS is properly installed on the system, enter
ccsboardinfo
at the Matlab command line. Matlab should return information similar to the following
listing:
iv
Board Board Proc Processor Processor
Num Name Num Name Type
--- --------------------------- --- --------------------------- --------------
0 C6713 DSK 0 CPU_1 TMS320C6x1x
To ensure Embedded Target for TI C6000 DSP is installed, enter
c6000lib
Matlab should display the C6000 block library containing the libraries: C6000 DSP Core
Support, C62x DSP Library, C64x DSP Library, C6416 DSK Board Support, C6701 EVM
Board Support, C6711 DSK Board Support, C6713 DSK Board Support, RTDX Instrumen-
tation, TMDX326040 Daughtercard Support.
0.5 Configuration Parameters for C6000 Hardware
This section describes how congure Simulink and Real-Time Workshop for use with the
C6713DSK. These conguration setting are required and are similar for all the experiments.
This is also the rst step before any experiment. Any deviations from these parameters are
indicated in the experiments.
1. Launch Matlab
2. At the Matlab command line, type
simulink
to launch Simulink
3. Create a new model in Simulink.
4. To open the Conguration Parameters, select SimulationConguration
Parameters
5. In the Select tree, chose the Real-Time Workshop category.
v
6. For Target Selection, choose the le ti c6000.tlc. Real-Time Workshop will automat-
ically change the Make command and Template makele selections.
7. Choose the Optimization category in the Select tree. For Simulation and Code
generation, un-select Block reduction optimization and Implement logic sig-
nals....
8. Choose the TI C6000 target sel.... Set Code generation target type to
C6713DSK.
9. Choose the TI C6000 compiler. Set Symbolic debugging and uncheck DSP/Bio
option.
10. In the Select tree, choose the Debug category. Select Verbose build here.
11. In the Select tree, choose the Solver category. Ensure that Solver is set to Fixed type
/ discrete.
vi
Chapter 1
Experiments
1.1 Experiment 1: Introduction to Simulink and Code Composer Studio
This experiment describes how to use Simulink in conjunction with code composer studio for
basic signal representation and manipulation. In this experiment, an audio eects processor
is created to echo, reveberation and ange. To run this model, a microphone is connected to
the Mic In connector of the C6713 DSK and speakers are connected to the Line Out of
the DSK. To download and run the model, the following tasks are completed:
Use blocks from Simulink and other blocksets to complete the model
Add the Embedded Target for TI C6000 DSP blocks that let your signal sources and
output devices communicate with your C6713 DSK
Add the C6713 DSK target preferences block from the C6000 Target Preferences library
to your model. Verify and set the block parameters for the target hardware.
Set the conguration parameters for the model, including
Conguration Parameters such as simulation start and stop time and solver
options.
Real-Time Workshop options such as target conguration and target compiler
selection
Build the model to the selected target.
vii
Test the model running on the target by changing the input to the target and observe
the output from the target.
1.1.1 Building a Simple I/O system with the C6713 DSK
File name: simpleioworks.mdl
To build the model for a Single Audio Eect, follow these steps:
1. Perform the steps in section 2.4.1 and 2.5.
2. The DSK has four input and output jacks: Headphone, Line Out, Line In, and
Mic In. The goal is to implement a system that accepts an audio signal via the Mic
In jack and passes that signal through, unchanged, to the Headphone jack.
3. Select the Simulink Library Browser window and select Embedded Target for TI C6000.
Within this group, select the C6713 DSK Board Support library. There will be ve (5)
blocks displayed: ADC, DAC, LED, Reset, and Switch.
4. Place the ADC (Analog-to-Digital Converter) and DAC (Digital-to-Analog Converter)
blocks on your model by clicking and dragging.
5. Once they are on your model, connect the two, as shown below:
6. Double clicking a block displays the block parameters. While some parameters are
userdenable, others are not. The ADC source eld can be set to either Iic In or Line
In. If the input is from the microphone then the eld should be set to Mic In; otherwise,
it should be set to Line In. In the ADC block, Stereo should be unchecked and the
output data type set to integer. NOTE: The sample rate can also be set here. For
most applications, this is either set to 8kHz (speech applications) or 44.1kHz (music
viii
applications). The Samples per Frame parameter tells the system how many samples to
process at one time. The greater the samples per frame, the longer it takes to process
the signal (due to memory needs and computational load).
7. Double click the DAC block. Ensure that the Word Length eld is the same (16-bit)
for both the ADC and DAC blocks.
8. Save the model:
Select File > Save As > ...location
9. Ensure that the hardware is connected properly by:
(a) Connecting the microphone to the Mic In jack.
(b) Connecting the headphones to the Headphone jack.
10. The model is now complete and ready to run. Verify that the DSK board is connected
properly .Use the Incremental Build command on the Simulink model toolbar (the
icon with the 3 arrows) to begin compiling the model and transferring the code to the
DSK.
11. If this is the rst time the board has been used since turning on the computer, a DSK
Startup window will open temporarily to congure the board.
12. the system will rst compile code in Matlab, then Code Composer Studio (CCS) will
be opened, where assembly code will be compiled and loaded onto the DSP. Once in
CCS, a progress window will open as the code is loaded onto the board.
13. The program (File Load Lab1.out), once loaded will begin to run. Test the model
by speaking into the microphone and listening to your speech through the headphones.
After verifying that the code works, stop the program by using the Halt command in
CCS. Close CCS and return to the model in Simulink.
ix
1.1.2 Designing a single echo effect in real time
File name : singleechoworks.mdl
In the above section, a basic I/O system for audio was built, compiled and run. This
section investigates data manipulation and representation on the DSK by designing a basic
audio processing system.
In this section, an echo lter is designed. An echo is a delayed, attenuated version of the
original signal. The dierence equation describing a system with a single echo is dened as
y[n] = x[n] +ax[n D], where a is the gain and D is the delay. The gure below shows the
Simulink block diagram that implements this. Simulink allows one to simulate models before
Figure 1.1: Basic I/O system
implementing them on the target hardware. This enables one to both debug the model and
quickly assess the eects of parameter changes.
1. To simulate the model in Simulink, change the model shown above so that the ADC is
replaced by Signal from Workspace and the DAC is replaced by Signal to Workspace.
2. In Matlab, load an input le, for example:
load audiofrag.mat
This le is sampled at 22050Hz. Set the input signal to
audiofrag
and the output signal to
echo
x
.
3. Run the simulation by clicking the play button. The text box to the left of the triangle
indicates how long (in seconds) the simulation will run for.
4. When the simulation has stopped, switch back to the Matlab window and listen to the
output that was created using the command:
soundsc(echo)
You should hear the echo.
5. In the Simulink model, change the delay and gain by double clicking on the desired
block and explore the eect of each on the output signal.
6. Now implement the single echo in real-time using the DSP board by replacing the
Signal from Workspace block with ADC and the Signal to workspace block with DAC.
The model should look like gure 3.2 below. Build and run the model (using the
Incremental Build button on the model toolbar).
7. Finally, from the TI C6000 Target Preferences block library, add the C6713DSK target
preferences block. This block is not connected to any other block in the model.
8. Test the model using the microphone (Mic In) and a pair of headphones (Headphone).
1.1.3 Real time audio reveberation model
File name:audiorevworks.mdl
In this section a model that simulates audio reveveration is created and built. Reverber-
ation is the result of an innite number of echoes added together, and can be represented
mathematically as y[n] = x[n] + ax[n D] by[n D], where a and b are the gains and D
is the delay. For this experiment, a microphone is connected to the Mic In connector on the
xi
Figure 1.2: Real time single echo lter
C6713 DSK and speakers (and an oscilloscope) connected to the Line Out connector on the
C6713 DSK. To test the model, speak into the microphone and listen to the output from the
speakers.
1.1.4 Building the audio reveberation model
1. Open Simulink.
2. Create a new model by selecting File - New - Model from the Simulink menu bar.
3. Use Simulink blocks to create the following model.
4. The Integer Delay block is in Discrete library of the Simulink blockset. The Gain block
is in the Commonly Used library of the simulink blockset. The Line In and Line Out
block for the C6713 DSK are in the C6713 Board Support library of the Embedded
Target for TIC6000 blockset.
5. From the TI C6000 Target Preferences block library, add the C6713DSK target pref-
erences block. This block is not connected to any other block in the model.
xii
Figure 1.3: Real time reveberation lter
6. Click the C6713 DSK ADC block to select it. Select Block Parameters from the
Simulink Edit menu. Set the following parameters for the block:
Select the +20 dB mic gain boost check box
For Output data type, select Double from the list
Set Scaling to Normalize
Set Source gain to 0.0
Enter 64 for Samples per frame
7. For ADC source, select Mic In.
8. Click OK to close the Block Parameters: ADC dialog.
9. Now set the options for the C6713 DSK DAC block.
Set Scaling to Normalize
For DAC attenuation, enter 0.0
xiii
Set Overow mode to Saturate.
10. Click OK to close the dialog.
11. Open the Conguration Parameters dialog, select Solver on the Select tree, and set the
appropriate options on the Solver pane for your model and for the target.
Under Solver options, select the xed-step and discrete settings from the lists.
Set the Fixed step size to auto and select Single Tasking for the Tasking mode.
12. Build and run the model (using the Incremental Build button on the model toolbar).
13. Speak into the microphone connected to the board. The model should generate a
reverberation eect out of the speakers, delaying and echoing the words you speak into
the mike.
1.1.5 Real time audio flange model
File name : audioflangerworks.mdl
A ange eect is an audio eect, which is achieved by combining to identical signal
with each other, with one signal delayed by a gradually changing amount. The dierence
equation for the ange eect is given by, y[n] = x[n] +ax[n d(n)], where the time varying
delay is given by, d(n) = D +
D
2
(1 sin(
2f
d
n
fs
)) where D is a xed delay, f
d
is the anging
frequency, and f
s
is the sampling rate. The gure below shows the Simulink block diagram
that implements this system.
1. Again, start by creating a simulation model of this system. It is identical to the rela
time model in the gure above except that the ADC and DAC are replaced by Signal
From Workspace and Signal To Workspace.
2. Load the audio le, audiofrag.mat, or your own recorded speech or music les. Run
the simulation.
xiv
Figure 1.4: Real time ange lter
3. You should hear the ange eect.
4. Now implement the Flange Eect system in real-time using the DSP board. The model
should look like gure 3.4. Build the model (using the Incremental Build button on
the model toolbar). Once the program is built, it will begin running on the DSK.
5. Test the system using recorded music or speech played through the Line In connector
of the DSK and a pair of headphones connected to the Headphone connector.
(The material in this lab handout is derived principally from S. Ganapathis M.Sc. thesis (2006).)
c 2006SG
xv

Vous aimerez peut-être aussi