8/12/2019 Dsp Lab Assignments
1/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 realor complex numeric data with one or more dimensions. The basic data objects of signalprocessing (one-dimensional signals or sequences, multichannel signals, and two-dimensionalsignals) are all naturally suited to array representation.
Matlab represents ordinary one-dimensional sampled data signals, or sequences, as vectors.Vectors are 1-by-nor 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 five-element real sequence in a row vector. It can be converted to a columnvector by taking the transpose:
x = [ 1 2 3 4 5 ]
Column vectors extend naturally to the multichannel case, where each channel is representedby a column of an array.
c2006GM
8/12/2019 Dsp Lab Assignments
2/112
Another method for creating vector data is to use the colon operator. Consider a 1-secondsignal 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 toone second in steps of one millisecond.
You can also use linspaceto 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. Analogsignals must be sampled in order to be processed digitally.
Samplingx(n) =xa(nTs)x is a discrete signal sampled from the analog signal xa with a sample periodofTs and asample frequencyofFs= 1/Ts.
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)
8/12/2019 Dsp Lab Assignments
3/112
An alternative to creating signals is to use a toolbox function. A variety of toolbox functionsgenerate waveforms . Each of them requires that you begin with a vector representing a timebase. 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, xa(t), isbandlimited, meaning that it doesnot contain any frequencies higher than a maximum frequency fM, the Shannon samplingtheorem says that it can be completely recovered from a set of samples if the samplingfrequencyfs is greater than two times the maximum frequency of the signal to be sampled:
Fs> 2fM
This maximum frequencyfMis known as theNyquist frequency. If the sampling frequency isnot greater than two times the Nyquist frequency, the continuous signal cannot be uniquelyrecovered and aliasingoccurs. (You heard examples of aliased signals in Homework No.1).
fs> 2fM: Original signal and sampled signal have the same frequency.fs 2fM: 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 fftfunction on the signal to determine the frequency).
8/12/2019 Dsp Lab Assignments
4/112
Signal Visualization
View signal amplitude vs. time index
Functions: plot, stem,stairs, strips Listen to data: sound
Note: the soundand soundsccommands will not work if your computer hardware isnt setup. 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 stripscommand do? (See help strips.)Q: What does the .*operator do?
Signal Processing Tool
The Signal Processing Toolbox application, SPTool, provides a rich graphical environmentfor signal viewing, filter design, and spectral analysis.
You can use SPTool to analyze signals, design filters, analyze filters, filter signals, and an-alyze signal spectra. You can accomplish these tasks using four GUIs that you access fromwithin SPTool:
The Signal Browseris for analyzing signals. You can also play portions of signals usingyour computers audio hardware.The Filter Designeris for designing or editing FIR and IIR digital filters. Note that the
8/12/2019 Dsp Lab Assignments
5/112
FDATool is the preferred GUI to use for filter designs. FDATool is discussed in later labs. The Filter Viewer is for analyzing filter characteristics. The Spectrum Viewer is for spectral analysis.
Open SPTool by typing sptoolat the command prompt.
Try:
sptool
Look at the train signal, FIRbp filter, and trainse spectrum. (You see 3 panes- Signals, Filters, Spectra. Filter Designer is available through File Preferences. Youcan play sounds using the LS icon. When viewing spectra, note that many methods ofdetermining spectra, including the fft, are available.)
Importing a Signal
You can use SPTool to analyze the signals, filters, or spectra that you create at the Matlabcommand line.
You can import signals, filters, or spectra from the Matlab workspace into the SPToolworkspace using the Importitem 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 (fand 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 agraphical view of the signal object(s) currently selected in teh Signalslist 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
8/12/2019 Dsp Lab Assignments
6/112
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 Shiftkey for multiple selections) in the Signalslist ofSPTool. Click the Viewbutton in the Signalslist 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 frequencyitem in the Editmenu.
3. Enter the desired sampling frequency and cliickOK.
Try changing the sampling rate of the imported signal.
Signal Generation
Signals Create a time base vectort = [0:0.1:2];
Create a signal as a function of timex = sin(pi*t/2);
plot(t,x)
Useful Matlab functions Nonperiodic functionsones, zeros
Periodic functionssin, cos, square, sawtooth
8/12/2019 Dsp Lab Assignments
7/112
Nonperiodic Signalst = 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 functionsstep, 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 widthw: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])
8/12/2019 Dsp Lab Assignments
8/112
SinusoidsSinusoid parameters Amplitude, A
Frequency, f Phase shift, Vertical offset, B
The general form of a sine wave is
y= Asin(2f t+) +B
Example: generate a sine wave given the following specifications: 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 isthe percentage of the time over one period that the amplitude is high.
Example: duty cycle is 50% (the Matlab default)
8/12/2019 Dsp Lab Assignments
9/112
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, youspecify 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)
8/12/2019 Dsp Lab Assignments
10/112
Complex Signals
Periodic signals can be represented by complex exponentials:
x(t) =ej2ft =cos(2f t) +jsin(2f t) =cos(t) +jsin(t)
Ift is measured in seconds, then fwill have units ofsec1, and will have units of radi-ans/second.
In signal processing, we associate the unit circle with one sampling cycle, so that a samplingfrequency ofFs is associated with 2 radians, and the Nyquist frequency Fs/2 is associatedwith radians. Values of in the upper half-plane, in units of Hz, then correspond tofrequencies within the sampled signal.
In Matlab, type:
x = exp(2*pi*j*f*t);
plot(x)
Matlab recognizes eitherj ori as the square root of -1, unless you have defined variables joriwith different values.
Useful Matlab functionsreal, imag, abs, angle
Try:
edit zsigzsig(5)
Look at both figures and describe what you see.
Importing Data
An important component of the Matlab environment is the ability to read and write datafrom/to external sources. Matlab has extensive capabilities for interfacing directly with datafrom external programs and instrumentation.
In this lab, we concentrate on reading and writing data that has already been stored inexternal files.
Files come in a variety of standard formats, and Matlab has specialized routines for workingwith each of them. To see a list of supported file formats, type:
help fileformats
8/12/2019 Dsp Lab Assignments
11/112
To see a list of associated I/O functions, type:
help iofun
Matlab provides a graphical user interface, theImport Wizard, to the various I/O functions.You access the Wizard by choosing File Import Dataor by typing:
uiimport
The Matlab command importdatais a programmatic version of the Wizard, accepting all ofthe default choices without opening the graphical user interface. You can use importdatainM-files to read in data from any of the supported file formats.
Matlab also has a large selection of low-level file I/O functions, modeled after those in the C
programming language. These allow you to work with unsupported formats by instructingMatlab to open a file in memory, position itself within the file, read or write specific formatteddata, and then close the file.
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 plotcommand.
I = importdata(eli.jpg);
image(I)
which theme.wav
uiimport
Browse for:
theme.wav
soundsc(data,fs)
8/12/2019 Dsp Lab Assignments
12/112
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 file (MAT-file)with a .matextension. The file is placed in the current directory.
The loadcommand reads variables from a MAT-file back into the Matlab workspace.
Although quite specialized, saveand loadcan be used for day-to-day management of yourMatlab 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 workspacetab 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 tomodel 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 andstretch:
8/12/2019 Dsp Lab Assignments
13/112
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 withmean 0 and standard deviation 1. To generate random numbers from a normal distributionwith mean muand 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 theStatistics 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 noisyCscript
8/12/2019 Dsp Lab Assignments
14/112
to generate swn.)
Pseudorandomness
This number:
0.95012928514718
is the first number produced by the Matlab uniform random number generator with itsdefault settings. Start up Matlab, set format long, type rand, and you get the number.
If all Matlab users, all around the world, all on different computers, keep getting this samenumber, is it really random? No, it isnt. Computers are deterministic machines andshould 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 pseudorandomnumbers.
A working definition 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 withstatisticians ...
Random number generators proceed deterministically from their current state. To view thecurrent state ofrand, type:
s = rand(state)
This returns a 35-element vector containing the current state.
To change the state ofrand:
rand(state,s) Sets the state tos.rand(state,0) Resets the generator to its initial state.rand(state, sum(100*clock)) Sets to a new state each time.
Commands forrandnare analogous.
Try:
s = rand(state)
format long
rand
8/12/2019 Dsp Lab Assignments
15/112
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 ahigher or lower rate.
y = downsample(x,n)
decreases the effective sampling rate ofx by keeping everynth sample starting with the firstsample. xcan be a vector or a matrix. Ifx is a matrix, each column is considered a separatesequence.
y = upsample(x,n)
increases the effective sampling rate ofx by insertingn 1 zeros between samples. xcan bea vector or a matrix. Ifx is a matrix, each column is considered a separate sequence. Theupsampledy has x n samples.
y = resample(x,p,q)
resamples the sequence in vectorx atp/qtimes the original sampling rate, using a polyphase
filter implementation. p and q must be positive integers. The length of y is equal toceil(length(x)p/q). Ifx is a matrix, resampleworks down the columns ofx.
y = interp(x,r)
increases the sampling rate ofx by a factor ofr. The interpolated vectory isr times longerthan the original input x.
y = decimate(x,r)
reduces the sampling rate ofx by a factor ofr. The decimated vector y is r times shorterin length than the input vector x. By default, decimateemploys an eighth-order lowpassChebyshev Type I filter. It filters the input sequence in both the forward and reverse
directions to remove all phase distortion, effectively doubling the filter order.
Try:
load mtlb
sound(mtlb,Fs)
mtlb4 = downsample(mtlb,4)
mtlb8 = downsample(mtlb,8)
sound(mtlb8,fs/8)
8/12/2019 Dsp Lab Assignments
16/112
What are the sizes ofmtlb, mtlb4, and mtlb8?(Ifsounddoesnt 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
Modulationvaries the amplitude, phase, or frequency of a carrier signal with reference to amessage signal.
The Matlab modulate function modulates a message signal with a specified modulationmethod. The syntax is
y = modulate(x,fc,fs,method)
where: x is the message signal. f cis the carrier frequency. f sis the sampling frequency. methodis a flag for the desired modulation method (see table below).
Method Descriptionamdsb-sc or am Amplitude modulation, double side-band, suppressed carrier
amdsb-tc Amplitude modulation, double side-band, transmitted carrieramssb Amplitude modulation, single side-band
fm Frequency modulationpm Phase modulation
ppm Pulse position modulationpwm Pulse width modulationqam Quadrature amplitude modulation
The demod function performs demodulation, that is, it obtains the original message signalfrom the modulated signal. The syntax is:
8/12/2019 Dsp Lab Assignments
17/112
x = demod(y,fs,fs,method)
demoduses any of the methods shown for modulate. The signalx is attenuated relative toy because demodulation uses lowpass filtering.
Exercise: High and Low
1. Create a signal equal to the sum of two sine waves with the following characteristics:3-second durationSampling frequency = 2 kHzSinusoid 1: frequency 50 Hz (low), amplitude 10, phase = 0Sinusoid 2: frequency 950 Hz (high), amplitude 1, phase = 0
2. View and listen to the signal using an M-file
3. Import the signal into SPTool and view it. Listen to the signal.
HAND IN:ANSWERS TO ALL QUESTIONS STARTING WITH THE LETTER Q INFRONT 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.)
c2006GM
8/12/2019 Dsp Lab Assignments
18/112
E E 2 7 5 Lab June 30, 2006
Lab 2. Spectral Analysis in Matlab
Introduction
This lab will briefly describe the following topics: Signal statistics Discrete Fourier Transform Power Spectral Density estimation Time-varying spectra
Wavelets
Statistical Signal Processing
Repeated measurements of a signalxunder identical environmental conditions typically yielddifferent waveforms. The valuex(n) of a signal at sample n is not a constant, but rather arandom variable with a certain distribution.
A signal isstationaryif its distribution at anynis independent of time shifts, i.e., ifx(n) and
x(n+N) have the same distribution for every integer N. Stationary signals are associatedwith steady states in the system producing the signal, and are characterized by constantaverages and variances along the signal. When statistics computed along any instance of asignal are identical to those computed across ensembles of different 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 coefficient (corrcoeff) of signal values sampled acrosstime or across ensembles. The Statistics Toolbox provides many additional statistical func-tions.
The Signal Processing Toolbox provides a crosscorrelation function (xcorr) and a crossco-variancefunction (xcov). Crosscorrelation of two signals is equivalent to the convolution ofthe two signals with one of them reversed in time. The xcorr function adds several optionsto the standard Matlab conv function. The xcovfunction simply subtracts the mean of theinputs before computing the crosscorrelation. The crosscorrelation of a signal with itself iscalled itsautocorrelation. It measures the coherenceof a signal with respect to time shifts.
c2006GM
8/12/2019 Dsp Lab Assignments
19/112
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 signaly. We can model y by
y(n) =x(n d) +
where is an attenuation factor, d is a time delay, and is channel noise. IfTis the returntime for the signal, then x and y should be correlated at n = T. The target will be locatedat a distance ofvT, 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)
8/12/2019 Dsp Lab Assignments
20/112
[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 analysisgives analternative view of time or space-based data in the frequency domain. The computationalbasis of spectral analysis is the discrete Fourier transform(DFT).
The DFT of a vector y of length n is another vectorYof length n:
Yk+1=n1
j=0
jkyj+1
where is a complexnth root of unity:
= e2i/n
This notation usesi for the complex unit, and j andk for indices that run from 0 to n 1.The subscriptsj +1 andk+1 run from 1 ton, corresponding to the range usually associatedwith Matlab vectors.
Data in the vector y are assumed to be separated by a constant interval in time or spacedt = 1/Fs. Fs is called the sampling frequency of y. The coefficientYk+1 measures theamount of the frequency f = k(Fs/n) that is present in the data in y. The vector Y iscalled thespectrumofy.
The midpoint ofY(or the point just to the right of the midpoint, ifnis even), correspondingto the frequencyf=F s/2, is called theNyquist point. The real part of the DFT is symmetricabout the Nyquist point.
The graphical user interface fftgui allows you to explore properties of the DFT. Ify is a
vector,fftgui(y)
plotsreal(y),imag(y),real(fft(y)), andimag(fft(y)). You can use the mouse to moveany of the points in any of the plots, and the points in the other plots respond.
Try:
Roots of unity
edit z1roots
8/12/2019 Dsp Lab Assignments
21/112
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 tocompute the DFT.
DFTs with a million points are common in applications. For modern signal and imageprocessing applications, and many other applications of the DFT, the key is the ability todo such computations rapidly. Direct application of the definition of the DFT requiresnmultiplications and n additions for each of the n coefficients - a total of 2n2 floating-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 microsecondwould require a million seconds, or about 11.5 days.
Modern FFT algorithms have computational complexity O(nlog2n) instead ofO(n2). Ifn
is a power of 2, a one-dimensional FFT of length n requires less than 3nlog2nfloating-pointoperations. Forn = 220, thats a factor of almost 35,000 times faster than 2n2.
When using the FFT, a distinction is often made between a window length and an FFTlength. The window length is the length of the input. It might be determined by, say, the
8/12/2019 Dsp Lab Assignments
22/112
size of an external buffer. The FFT length is the length of the output, the computed DFT.The command
Y=fft(y)
returns the DFTY ofy. The window length length(y)and the FFT length length(Y)arethe same.
The command
Y=fft(y,n)
returns the DFTY with lengthn. If the length ofy is less than n,y is padded with trailingzeros to lengthn. If the length ofy is greater thann, the sequencey is truncated. The FFTlength 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 fftfunction is based on FFTW, The fastest Fourier Transform in the West,
developed by MIT graduate students Matteo Frigo and Steven G. Johnson. (http://www.fftw.org)
Spectral Analysis with the FFT
The FFT allows you to estimate efficiently the component frequencies in data from a discreteset of values sampled at a fixed rate. The following list shows the basic relationships amongthe various quantities involved in any spectral analysis. References to time can be replacedby references to space.
y Sampled datan = length(y) Number of samplesFs Samples/unit timedt = 1/Fs Time incrementt = (0:n-1)/Fs Time rangeY = fft(y) Discrete Fourier Transform (DFT)abs(Y) Amplitude of the DFTabs(Y).^2/n Power of the DFTFs/n Frequency increment
8/12/2019 Dsp Lab Assignments
23/112
f = (0:n-1)*(Fs/n) Frequency rangeFs/2 Nyquist frequency
A plot of the power spectrum is called aperiodogram. The first half of the principal frequencyrange (from 0 to the Nyquist frequency Fs/2 is sufficient, because the second half is areflection of the first half.
Spectra are sometimes plotted with a principal frequency range from Fs/2 toF s/2. Matlabprovides the function fftshiftto rearrange the outputs offft and convert to a 0-centeredspectrum.
Try:
Periodograms
edit pgrams
pgrams
Whale calledit whalefft
whalefft
FFT Demossigdemo1
playshow fftdemo
phone
playshow sunspots
If youre not familiar with DTMF, try the following with a touch-tone telephone. Whilelistening to the receiver, press two keys in the same row simultaneously, then press two keysin 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 harmonicsshow 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 theprincipal range, confusing the frequency analysis.
8/12/2019 Dsp Lab Assignments
24/112
Power Spectral Density (PSD)
The power spectral density (PSD) of an analog signal y is a function of frequency, Ryy(f),
whose area equals the total signal power. Its units are, e.g., watts/hertz, and Ryy(f)fapproximates signal power over a small range of frequencies fcentered atf. The Wiener-Khintchine theorem states that Ryy(f) is the DFT of the autocorrelation function ryy(t) ofy. The value Ryy(0) =ryy(0) gives the average power in the signal.
For signals sampled over a finite interval of time, the best we can do is estimate the PSD. Thisresult is because the spectra of finite sequences suffer from both poor resolution andleakage(nonzero spectral components at frequencies othe than harmonics ofy due to sampling overnoninteger multiples of the signal period).
PSD estimates of noisy analog signals from a finite number of its samples are based on three
fundamentally different approaches:
Non-parametric methodsMake no assumptions about the data in the sample and work directly with the DFT.Welch: pwelchMultitaper: pmtm
Parametric methodsModel the data in the sample as the output of a linear system excited by white noise (noisewith zero mean and constant PSD), estimate the filter coefficients, and use these to estimatethe PSD.Burg: pburgYule-Walker: pyulear
Subspace methodsBased on an eigenanalysis or eigendecomposition of the correlation matrx associated withthe data in the sample.EV: peigMUSIC: 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;
8/12/2019 Dsp Lab Assignments
25/112
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 suchmethod is the periodogram. An improved version of the periodogram is Welchs method. Amore 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 thesame length as P xx.
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 vectorx is segmentedinto equal-length sections with overlap. Trailing entries not included in the final segmentare discarded. Each segment is windowed. Optional inputs specify windows (default isHamming), 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 frequencydomain). The quantitynw is the time-bandwidth product for the discrete prolate spheroidalsequences specifying the tapers. Optional inputs specify taper frequencies, FFT length, andPSD sample frequencies.
Try:
8/12/2019 Dsp Lab Assignments
26/112
t = 0:1/100:10-1/100;
x = sin(2*pi*15*t) + sin(2*pi*30*t);
periodogram(x,[],512,100);
figurepwelch(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 wherethe signal length is short. These methods use a different approach to spectral estimation:instead of estimating the PSD directly from the data, they model the data as the output ofa linear system driven by white noise (an adaptive filter), and then attempt to estimate theparameters of that linear system.
The most commonly used linear system model is the all-pole model, a system with all of itszeros at the origin in the z-plane. The output of such a system for white noise input is anautoregressive (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 PSDat certain frequencies. The data in many practical applications (such as speech) tends tohave peaky spectra, so that AR models are often useful. In addition, the AR models lead toa system of linear equations that is relatively simple to solve.
The following methods are summarized on the next page. The inputp specifies the order ofthe 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 modified covariance methods[Pxx f] = pcov(x,p,nfft,fs)
[Pxx f] = pmcov(x,p,nfft,fs)
8/12/2019 Dsp Lab Assignments
27/112
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 summarizedin the following table. See the documentation for further details.
Burg Covariance Modified Yule-WalkerCovariance
CharacteristicsDoes not apply Does not apply Does not apply Applies windowwindow to data window to data window to data to data
Minimizes forward Minimizes forward Minimizes forward Minimizes forwardand backward prediction error and backward prediction error
prediction errors prediction errors
Advantages
High resolution for Better resolution High resolution for As good as othershort data records than Y-W for short short data records methods for large
data records data recordsAlways produces Extract frequencies Extract frequencies Always producesa stable model from mix ofp or from mix of p or a stable model
more sinusoids more sinusoidsNo spectral
line-splitting
Disadvantages
Peak locations Can produce Can produce Performs relativelyhighly dependent unstable models unstable models poorly for shorton initial phase data records
Spectral line- Frequency bias Peak locations Frequency biassplitting for for estimates of slightly dependent for estimates of
sinusoids in noise, sinusoids in noise on initial phase sinusiods in noiseor when order is
very largeFrequency bias for Minor frequencysinusoids in noise bias for sinusiods
in noise
8/12/2019 Dsp Lab Assignments
28/112
Conditions for Nonsingularity
p must be 1/2 p must be 2/3 Autocorrelationinput frame size input frame size matrix always
positive-definite,nonsingular
Subspace Methods
Subspace methods, also known as high-resolution methodsor super-resolution methods, gen-erate PSD estimates based on an eigenanalysis or eigendecomposition of the correlationmatrix. These methods are best suited for line spectra - i.e., spectra of sinusoidal signals -and are effective 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 ofsinusoidal components in a signal) of the input signal x, and a vector w of normalizedfrequencies (in rad/sample) at which the pseudospectrum is evealuated. The input pcontrolsthe dimensions of the signal and noise subspaces used by the algorithms.
Eigenvector method[S f] = peig(x,p,nfft,fs)
Multiple Signal Classification (MUSIC) method[S f] = pmusic(x,p,nfft,fs)
The MUSIC algorithm uses Schmidts eigenspace analysis method. The eigenvector uses aweighted 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 different methods. To create aspectrum in SPTool,
8/12/2019 Dsp Lab Assignments
29/112
8/12/2019 Dsp Lab Assignments
30/112
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 signalsoriginal 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 thesignal remain recognizable long after the original spectrogram has become obscured. This isa tribute to the human auditory system, and is the basis of signal compression algorithmsused 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, butfor time-varying or bursty signals, time can be critical to an analysis.
The time-dependent Fourier transform computed by the specgram function is one solutionto this problem. By applying a DFT to a sliding window in the time domain, specgramcaptures a signals frequency content at different times. The disadvantage of this methodis that it is uniformon all time intervals: it does not adjust to local idiosyncrasies in thefrequency content. As a result, more subtle nonstationary characteristics of a signal can goundetected.
8/12/2019 Dsp Lab Assignments
31/112
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 mightmiss.
A wavelet is a waveform of effectively limited duration that has an average value of zero.
The discrete wavelet transform(DWT) computes coefficients of similaritybetween a signaland a sliding wavelet. The coefficients are found with wavelets of different scales(widthsthat approximate different frequencies) to analyze the signal at different resolutions. In awavelet analysis, a signal is iteratively decomposed into the sum of a lowpass approximationand a progressive sequence of highpass details.
The Wavelet Toolbox adds wavelet analysis techniques to the signal processing techniquesavailable in the Signal Processing Toolbox.
wavemenubrings up a menu for accessing graphical tools in the Wavelet Toolbox.
Try:
wavemenu
SelectWavelet 1-Dand thenFile Example Analysis Basic Signals Frequency breakdown
Sis the signala5 is the approximation
dn 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.)
c2006GM
8/12/2019 Dsp Lab Assignments
32/112
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:
linearify[N] is a linear combination of values ofx[n] andy[n] forn N. A differenceequation expressing this relation must not include constants or nonlinear functions ofxandy .
time-invariantifx[nN] produces outputy[nN] for anyN. That is, the system re-sponse does not change over time. Difference equation coefficients must not be explicitfunctions ofn.
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 befound by superposition.
An arbitrary LTI system can be completely described by its impulse response. The impulseresponse h[n] is the response of the system to a unit impulse at n = 0. In Matlab, vectorssubscripts start at 1, so we will define the impulse response as the response of the system toa unit impulse atn = 1. By superposition, the response of the system to an arbitrary inputx[n] can be described as a linear combination of scaled and shifted impulse responses, givingrise 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)
c2006GM
8/12/2019 Dsp Lab Assignments
33/112
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: Difference Equations
Matlabs Signal Processing Toolbox provides several models for representing linear, time-invariant systems. Difference equations describe the input/output behavior of an LTI systemdirectly in terms of signal values.
Nk=0
aky[n k] =Mm=0
bmx[nm]
y[n] =Mm=0
bmx[nm]Nk=1
aky[n k]
Note the summation limits in the two equations.
A difference 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 ofy), the system is said to berecursive. It will have an infinite impulse response(IIR). Whena is zero, the system is saidto be nonrecursive. It will have a finite impulse response(FIR).
What does a non-zero a imply in terms of the connections in a filter block dia-gram (where the blocks represent delays)?
Example:Represent the following difference equation as two vectors:
8/12/2019 Dsp Lab Assignments
34/112
8/12/2019 Dsp Lab Assignments
35/112
8/12/2019 Dsp Lab Assignments
36/112
The leading coefficient in the numerator,k, is called the gain.
Example:
H(z) = z2 + 2z
z2 + 0.2
Zeros:
z2 + 2z= 0z(z+ 2) = 0z= 0 and z= 2
Poles:
z2 + 0.2 = 0
z= 0.2j
Gain:
k= 1
The location of the zeros and poles of the transfer function determines the response of anLTI 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)
finds the zeros z, poles p, and gain k from the coefficients b and aof a transfer function indiscrete filter form.
[z p k] = tf2zp(b,a)
finds the zeros z, poles p, and gain k from the coefficients b and aof a transfer function inproper form.
There is no difference betweentf2zpk and tf2zp if the lengths of the filter coefficient vectorsare first equalized using eqtflength.
8/12/2019 Dsp Lab Assignments
37/112
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 phaseanalysis.
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 filters, are often designed by positioning zeros and poles inthe z-plane. The strategy is to identify passband and stopband frequencies on the unit circleand then position zeros and poles by considering the following.
1. Conjugate symmetryAll poles and zeros must be paired with their complex conjugates.
2. CausalityTo ensure that the system does not depend on future values, the number of zeros mustbe less than or equal to the number of poles.
3. OriginPoles and zeros at the origin do not affect the magnitude response.
4. StabilityFor a stable system, poles must be inside the unit circle. Pole radius is proportional tothe gain and inversely proportional to the bandwidth. Passbands should contain poles
near the unit circle for larger gains.
5. Minimum phaseZeros 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 containzeros on or near the unit circle.
6. Transition bandA steep transition from passband to stopband can be achieved when stopband zerosare paired with poles along (or near) the same radial line and close to the unit circle.
8/12/2019 Dsp Lab Assignments
38/112
7. Zero-pole interactionZeros and poles interact to produce a composite response that might not match designgoals. 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 ahigher filter order.
Zero-Pole-Gain Editing in SPTool
Run:sptool
To access the Pole/Zero Editor in SPTool, do the following:1. Click the Newbutton under the Filters list in SPTool.
2. Select the Pole/Zero Editor in the Algorithmlist.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 systemrepresentations.
Note: Representation conversions can produce systems with slightly different characteristics.This difference is due to roundoff error in the floating point computations performed duringconversion.
8/12/2019 Dsp Lab Assignments
39/112
Transfer State Zero Partial Lattice Second Convolution
Function Space Pole Fraction Filter Order Matrix
Gain Sections
Transfer tf2ss tf2zp residuez tf2latc tf2sos convmtxFunction 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 responseh[n] and its z-transform (the transfer functionH(z)) completely char-acterize the response of an LTI system. For input x[n] in the time domain (X(z) in thefrequency domain), the output of the system y[n] in the time domain (Y(z) in the frequencydomain) is given by:
y[n] =x[n] h[n] (convolution) Time domainY(z) =X(z)Y(z) (product) Frequency domain
8/12/2019 Dsp Lab Assignments
40/112
8/12/2019 Dsp Lab Assignments
41/112
8/12/2019 Dsp Lab Assignments
42/112
Group delay Impulse response Step response Pole-zero plot Filter coefficients
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 selectingAnalysis Parameters Export the display to a file with Exporton 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 filters, and the process of generating the outputy [n] froman inputx[n] is called filtering. To filter a signal using a system described by transfer func-tion coefficients b anda, use the Matlab filter function.
y=filter(b,a,x)
filters the data in vector x with the filter described by numerator coefficient vector b anddenominator coefficient vector a. If a(1) is not equal to 1, filter normalizes the filtercoefficients bya(1). Ifa(1) equals 0,filter returns an error.
Thefilter function is implemented in a direct form II transposed filter architecture.
This is the difference 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]wheren1 is the filter 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;
8/12/2019 Dsp Lab Assignments
43/112
sw = sin(2*pi*262.62*t); % Middle C
n = 0.1*randn(size(sw));
swn = sw + n;
Use a simple lowpass (averaging) filter: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 (filter and conv) differ?
Using SPTool
Choose File Import from the SPTool main menu.Try importing the filter just created.
To apply a Filter in SPTool:1. Select the signal to be filtered.2. Select the filter to apply.3. Click the Apply button under the Filters list.
Try filtering the noisy middle C signal swnwith the simple lowpass filter created earlier.
Exercises:1. Plot the frequency responses of the two filters with the following difference 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] (finite differencing)2. Filter the signal x from Exercise 1 with each of the filters. (Run hilo to recreate thesignal.) View and listen to the outputs. Note that the two components of x are at 5% and95% of the Nyquist frequency, respectively.
3. Open each filter in the Pole/Zero editor in SPTool. Adjust the locations of the poles and
8/12/2019 Dsp Lab Assignments
44/112
zeros and observe the effects on both the response and the filtered 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 termsof system parameters, a deconvolution must be performed. Cepstral analysis is a commontechnique for such deconvolution.
The technique is based on two facts: a convolution in the time domain becomes a productin the z-domain, and logarithms of products become sums. If:
x[n] =x1[n] x2[n] X(z) =X1(z)X2(z)
then:
X(z) =log(X(z)) = log(X1(z)) +log(X2(z)) x[n] = x1[n] + x2[n]
The convolved signals become additive in the new cepstral domain. (The word cepstralreverses the first letters in the word spectral to reflect the back-and-forth between the timeand frequency domains.)
The complex cepstrum x[n] of a sequence x[n] is calculated by finding the complex naturallogarithm of the Fourier transform ofx, then the inverse Fourier transform of the resultingsequence:
x[n] = 1
2
log[X(ej)]ejnd
The Signal Processing Toolbox functionccepsperfoms this operation and the function iccepsperforms the inverse.
Thereal cepstrum(or just thecepstrum) ofx[n] is found as above, using only the magnitudeof the Fourier transform. It is computed by the Signal Processing Toolbox functionrceps.The original sequence cannot be reconstructed from only its real cepstrum, but you canreconstruct a minimum-phase version of the sequence by applying a windowing function inthe cepstral domain. The minimum phase reconstruction is returned by rceps in a secondoutput argument.
Read theechodetect.mscript (shown below), then try running it. (You might need to disablethe sound line.)
8/12/2019 Dsp Lab Assignments
45/112
% 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 = s 0 + a * s 1 + a2*s2 + a3*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
8/12/2019 Dsp Lab Assignments
46/112
8/12/2019 Dsp Lab Assignments
47/112
Calculate a normalizing factor:fs = 1e4;
f = 400;
nf = 400/(fs/2)
Filter Specifications in Matlab Wp - Passband cutoff frequencies (normalized) Ws - Stopband cutoff 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 specifications graphically:
fdatool
The order of the filter will increase with more stringent specifications: decreases in Rp, Rs,or the width of the transition band.
IIR Filter Design
The primary advantage of IIR filters over FIR filters is that they typically meet a given setof specifications with a much lower filter order than a corresponding FIR filter.
Although IIR filters have nonlinear phase, data processing in Matlab is commonly performedoff-line, that is, the entire data sequence is available prior to filtering. This allows fora noncausal, zero-phase filtering approach (via the filtfilt funtion), which eliminates thenonlinear phase distortion of an IIR filter.
The classical IIR filters - Butterworth, Chebyshev Types I and II, elliptic, and Bessel - allapproximate the ideal brick wall filter in different ways. The Signal Processing Toolboxprovides functions to create all these types of IIR filters in both the analog and digitaldomains (except Bessel, for which only the analog case is supported), and in lowpass, high-pass, bandpass, and bandstop configurations. For most filter types, you can also find the
lowest filter order that fits a given filter specification in terms of passband ripple, stopbandattenuation, 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;
8/12/2019 Dsp Lab Assignments
48/112
t = 0:1/fs:5;
sw = sin(2*pi*262.62*t);
n = 0.1*randn(size(sw));
swn = sw + n;
Create a Butterworth filter of order 2 with a cutoff at 400 Hz:[b a] = butter(2, 400/(fs/2));
Note the nonlinear phase:figure, freqz(b,a)
Now create a filter with filter:
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 filterProvides the best Taylor series approximation to the ideal lowpass filter response atanalog frequencies = 0 and = ; for any ordern, the magnitude squared responsehas 2n 1 zero derivatives (that is, it is maximally flat) at these locations. Responseis monotonic overall, decreasing smoothly from = 0 to = .
Chebyshev Type I filterMinimizes the absolute difference between the ideal and the actual frequency responseover the entire passband by using an equal ripple in the passband. Stopband responseis maximally flat. The transition from passband to stopband is more rapid than forthe Butterworth filter.
Chebyshev Type II filterMinimizes the absolute difference between the ideal and the actual frequency responseover the entire stopband by using an equal ripple in the stopband. Passband responseis maximally flat. The stopband does not approach zero as quickly as the type I filter(and does not approach zero at all for even-valued filter ordern). The absence of ripplein the passband, however, is often an important advantage.
8/12/2019 Dsp Lab Assignments
49/112
8/12/2019 Dsp Lab Assignments
50/112
8/12/2019 Dsp Lab Assignments
51/112
8/12/2019 Dsp Lab Assignments
52/112
Direct IIR Design
Direct design methods find a filter based on specifications in the discrete domain. Unlike the
analog prototyping method, direct designs are not constrained to the standard lowpass, high-pass, bandpass, or bandstop configurations. Filters with an arbitrary, perhaps multiband,frequency response are possible.
Theyulewalkfunction designs IIR digital filters by fitting a specified frequency response. Itfinds the inverse FFT of the ideal desired power spectrum and solves modified Yule-Walkerequations 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 coefficients ofthe ordern IIR filter whose frequency-magnitude characteristics approximate those given in
vectorsfandm. fis a vector of frequency points ranging from 0 to 1, where 1 represents theNyquist frequency. m is a vector containing the desired magnitude response at the pointsinf. f andm can describe any peicewise linear magnitude response, including a multibandresponse.
Note that yulewalk does not accept phase information, and no statements are made aboutthe optimality of the resulting filter.
Example: Arbitrary Response IIR Filter
Problem
Design a 12th-order bandstop filter fitting 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 fit 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:
8/12/2019 Dsp Lab Assignments
53/112
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
8/12/2019 Dsp Lab Assignments
54/112
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-finish filter design. Its graphical user interface, theFDATool, supports many advanced techniques not available in SPTool.
Use the FDATool to: Design filters Quantize filters Analyze filters Modify existing filter designs Realize Simulink models of quantized direct form FIR filters Perform digital frequency transformations of filters
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
Analysisbutton on the toolbar.
The FVTool is dynamically linked to the FDATool, so changes to a filter design automaticallyupdate plotted responses for analysis.
Importing Existing Filters
The FDATool can be used to edit and analyze existing filters by importing them from theMatlab workspace. To do so:1. Select Import Mode.
2. Choose the desired Filter Structure.3. Enter the coefficients.4. Enter the Sampling Frequency.5. Click Import Filter.
8/12/2019 Dsp Lab Assignments
55/112
8/12/2019 Dsp Lab Assignments
56/112
E E 2 7 5 Lab June 30, 2006
FIR Filters in Matlab
Lab 5. FIR Filter Design in Matlab
Digital filters with finite-duration impulse reponse (all-zero, or FIR filters) have both advan-tages and disadvantages when compared to infinite-duration impulse response (IIR) filters.
FIR filters 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 efficiently in hardware. The filter startup transients have finite duration.
The primary disadvantage of FIR filters is that they often require a much higher filter orderthan IIR filters to achieve a given level of performance. Correspondingly, the delay of thesefilters is often much greater than for an equal performance IIR filter.
FIR Methods
The Signal Processing Toolbox supports a variety of methods for the design of FIR filters.
F ilterMethod Description F ilterF unctionsWindowing Apply window to truncated inverse fir1, fir2, kaiserord
Fourier transform of desired filterMultiband with Equiripple or least squares approach firls, firpm, firpmord
Transition Bands over frequency subbandsConstrained Least Minimize squared integral error over fircls, fircls1
Squares entire frequency range subject to maximumerror constraints
Arbitrary Response Arbitrary responses, including nonlinear cfirpmphase and complex filters
Raised Cosine Lowpass response with smooth, firrcossinusoidal transition
c2006GM
8/12/2019 Dsp Lab Assignments
57/112
Impulse Response Revisited
FIR filters are described by difference equations of the form
y(n) =M
m=0
bmx(nm)
where the filtered signal y(n) is just a linear combination of current and previous valuesof the input signal x(n). The coefficients b are the numerator coefficients of the transferfunction. The denominator of the transfer function will always be a= 1. The order of thefilter is n = length(b) 1.
If the input signal is the unit impulsex= [1 0 00 ...], then the corresponding impulse response
y(n) =h(n) is identical to b(n):
h(0) =b0x(0) =b0h(1) =b0x(1) +b1x(0) =b1h(2) =b0x(2) +b1x(1) +b2x(0) =b2 ...etc.
The FIR filter coefficients give the impulse response.
Try this:
b = [-1 0 2 -3 1]; % no need to specify the a coefficientsstem(b)
figure, impz(b,1)
Why are the x-axis scales different?
Linear Phase Filters
A filter whose impulse response is symmetric about its midpoint is called a (generalized)
linear phasefilter. For such filters, The DFT of the impulse response will be either purely real or purely imaginary. The magnitude of the DFT is scaled by the filters magnitude response (there is no ampli-tude distortion). The phase shift of a filtered signal will vary linearly with frequency (pure time delaywith no phase distortion). The phase delay ()/ and group delay d()/d() will be equal and constant. Foran ordern linear phase FIR filter, the phase delay and group delay is n/2.
8/12/2019 Dsp Lab Assignments
58/112
The absence of either amplitude distortion or phase distortion preserves the waveform ofsignals in the passband.
Except for cfirpm, all the FIR filter design functions in the Signal ProcessingToolbox design linear phase filters 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 filter can have an odd or an even numberof points,and can have an odd or even symmetry about the midpoint, leading to four filtertypes:
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 filter type, certain restrictions apply:
F ilter F ilter Symmetry ResponseH (0) ResponseH(1)T ype Order (Nyquist)
Type I Even b(k) =b(n+ 2 k), k= 1,...,n+ 1 No restriction No restrictionType II Odd b(k) =b(n+ 2 k), k= 1,...,n+ 1 No restriction H(1) = 0Type 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 fir1, fir2, firls, firpm, fircls, fircls1, and firrcosall design type I and II linearphase FIR filters by default. Bothfirlsand firpmdesign type III and IV linear phase FIRfilters given a hilbertor differentiator flag. The function cfirpmcan design any type oflinear or nonlinear phase filter.
8/12/2019 Dsp Lab Assignments
59/112
Because the frequency response of a type II filter is zero at the Nyquist frequency (highfrequency),fir1 does not design type II highpass and bandstop filters. For odd-valuedn inthese cases, fir1adds 1 to the order and returns a type I filter.
Window-Based Design
Windowingis a common design method for FIR filters. 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 filter because it is infiniteand noncausal. h(n) is symmetrically truncated (multiplied by a finite, symmetric window) to create alinear phase finite impulse response.
The approximation to the ideal filter is best in a mean square sense, compared to otherapproximations of the same length, by Parsevals theorem. However, the abrupt truncationleads to overshoot (Gibbs phenomenon) and ripples in the spectrum. The undesirable effectsof truncation are reduced or eliminated by the use of tapered windows.
Windowing does not explicitly impose amplitude response constraints, such as passbandripple or stopband attenuation. It must be used iteratively to produce designs that meetsuch specifications.
Try:
edit windemo
windemo(20)
windemo(50)
windemo(100)
What do the arguments (20, 50, 100) specify?How does the filter change with the argument?
Windowing Functions
The Signal Processing Toolbox supports a variety of windows commonly used in FIR filterdesign. Typing
help window
provides a list of available functions:
8/12/2019 Dsp Lab Assignments
60/112
8/12/2019 Dsp Lab Assignments
61/112
Explain the yand wyplots.
Windowing and Spectra
When a signal is truncated, high-frequency components are introduced that are visible inthe DFT. By windowing the truncated signal in the time domain, endpoints are assigned areduced weight. The effect on the DFT is to reduce the height of the side lobes, but increasethe 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 11
0.5
0
0.5
1Truncated Signal
0 1 2 3 4 5 6 7 8 9 100
10
20
30
40
50DFT of Truncated Signal
Magnitude
Tuncated, windowed signal and DFT:
8/12/2019 Dsp Lab Assignments
62/112
8/12/2019 Dsp Lab Assignments
63/112
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 WindowVisualization Tool.
Use WVTool fordisplayingand comparing existing windows created in the Matlab workspace.
Use WinTool to interactivelydesign
windows with certain specifications and export themto the Matlab workspace.
Most window types satisfy some optimality criterion. Some windows are combinations ofsimpler windows. For example, the Hann window is the sum of a rectangular and a cosinewindow, and the Bartlett window is the convolution of two rectangular windows. Otherwindows emphasize certain desirable features. The Hann window improves high-frequencydecay (at the expense of larger peaks in the side lobes). The Hamming window minimizesside lobe peaks (at the expense of slower high-frequency decay). The Kaiser window hasa 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 aconvolution in the frequency domain.
An optimal time-limited window maximizes energy in its spectrum over a given frequencyband. In the discrete domain, the Kaiser window gives the best approximation to such anoptimal window.
wintool
opens WinTool with a default 64-point Hamming window. Try it - experiment with different
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?
8/12/2019 Dsp Lab Assignments
64/112
8/12/2019 Dsp Lab Assignments
65/112
8/12/2019 Dsp Lab Assignments
66/112
1. Design a windowed FIR bandstop filter to remove the 300 Hz component from the three-tone signal with noise y from Lab IIR Filters in Matlab. Use a sampling frequency of8192 Hz.
2. Plot the response.
3. Filter the signaly with the designed filter.
4. Compare signals and spectra before and after filtering.
Arbitrary Response FIR Filters
Thefir2function also designs windowed FIR filters, but with an arbitrarily shaped piecewiselinear frequency response. (The IIR counterpart of this function is yulewalk).
b=fir2(n,f,m);
returns row vectorb containing then +1 coefficients of an ordernFIR filter. The frequency-magnitude characteristics of this filter match those given by vectors f andm.
b=fir2(n,f,m,window);
uses the window specified in column vectorwindowfor the design. The vector window mustbe n+ 1 elements long. If you do not specify a window, fir2applies a Hamming window.
The functioncfirpmis used to design complex and nonlinear-phase equiripple FIR filters. Itallows arbitrary frequency-domain constraints.
Try:
edit directstop2
directstop2(10)
directstop2(100)
directstop2(500)
edit nlinphase
nlinphase
8/12/2019 Dsp Lab Assignments
67/112
Multiband Filters
The function firls designs linear-phase FIR filters that minimize the weighted, integrated
squared error between an ideal piecewise linear function and the magnitude response of thefilter over a set of desired frequency bands.
b=firls(n,f,a)
returns row vectorbcontaining then+1 coefficients of the ordernFIR filter whose frequency-amplitude characteristics approximately match those given by vectors f anda.
The function firlsallows you to introduce constraints by defining upper and lower boundsfor the frequency response in each band.
The function fircls1 is used specifically to design lowpass and highpass linear phase FIRfilters using constrained least squares.
Try:
edit firlsdemo
firlsdemo
edit firclsdemofirclsdemo
Raised Cosine Filters
The sinc function, which is the impulse response of an ideal lowpass filter, forms the basisfor several other interpolating functions of the form
h(n) =f(n)sinc
n
ns
, where f(0) = 1
One commonly-used form is the raised cosinefunction:
hrc(n) =cos(R n
ns)
1 (2R nns
)2sinc
n
ns
, 0 R 1
R is called the rolloff factor. Like the sinc function, the raised cosine function is 1 at n= 0and 0 at all other sampling instances n = ns. In contrast to the sinc function, the raisedcosine has faster decaying oscillations on either side of the origin for R >0. This results in
8/12/2019 Dsp Lab Assignments
68/112
improved reconstruction if samples are not acquired at exactly the sampling instants (i.e., ifthere is jitter). It also uses fewer past and future values in the reconstruction, as comparedto the sinc function. The shape of the functions spectrum is the raised cosine.
The ideal raised cosine lowpass filter 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 rolloff 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 filter with a raised cosinetransition band. The cutoff frequency is F0, the transition bandwidth df, and sampling
frequency is f s, all in hertz. dfmust be small enough so that F0 df /2 is between 0 andf s/2. bis 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 rolloff 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 onlya finite length buffer 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 filter coefficients (impulse response) and each block of data are transformed to the fre-quency domain using the FFT, where they can be efficiently convolved using multiplication.The partial convolutions of the signal are returned to the time domain with the IFFT, wherethey are shifted and summed using superposition.
8/12/2019 Dsp Lab Assignments
69/112
fftfilt implements the overlap-add method for FIR filters.
y=fftfilt(b,x)
uses an FFT length ofnfft= 2nextpow2(n) and a data block length ofnfft-length(b)+1 (ensurescircular convolution).
firfilt incurs an offline startup cost when converting the coefficients b to the frequencydomain. After that, the number of multiplications fftfiltperforms relative to filter (whichimplements the filter in direct form) is log2(L)/N, whereLis the block length andNis thefilter length. (Multiplications are a good measure of performance, since they are typicallyexpensive on hardware.) The net result is that for filters of high order, fftfiltoutperformsfilter.
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 fftfilt 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.)
c2006GM
8/12/2019 Dsp Lab Assignments
70/112
E E 2 7 5 Lab June 30, 2006
Lab 6. Advanced Filter Design in Matlab
Introduction
This lab will briefly 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 insufficient to perform the required filtering.
A simple example of a nonlinear filtering technique is median filtering. The Signal Process-ing Toolbox function medfilt1 implements one-dimensional median filtering by applying a
sliding window to a sequence. The filter replaces the center value in the window with themedian value of all the points within the window.
y = medfilt1(x,n)
applies an ordern (window lengthn) one-dimensional median filter to vectorx. The functionconsiders 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
8/12/2019 Dsp Lab Assignments
71/112
A two-dimensional median filtering function, medfilt2, is available in the Image ProcessingToolbox.
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 filters that optimallymeet filter requirements.
iirlpnorm
uses a least-pth norm unconstrained optimization algorithm for IIR filters that have arbitraryshape magnitude response curves. The algorithm differs from the traditional IIR designalgorithms 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 different. You can design IIR filters with arbitrary magnitude response in addition to the basiclowpass, highpass, bandpass, and bandstop.
iirlpnormc
uses a least-pth norm optimization algorithm as well, but this version is constrained to letyou restrict the radius of the poles of the IIR filter.
iirgrpdelay
uses a least-pth constrained optimization algorithm to let you design allpass IIR filters thatmeet a prescribed group delay specification.
The Demos section of the documentation for the Filter Design Toolbox includes examplesfor 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
8/12/2019 Dsp Lab Assignments
72/112
Try the demos on IIR filter 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 filters that optimallymeet filter requirements.
firgr
provides a minimax, or equiripple algorithm that allows you to design the following real FIRfilters: 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
TheDemossection 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 Efficient Narrow Transition Band FIR FIlter Design Halfband FIR Filter Design
Try the demos on FIR filter design in the documentation for the Filter Design Toolbox.
Adaptive Filters
Adaptive filters are self-learning systems. As an input signal enters the filter, the coefficientsadjust themselves to achieve a desired result. The result might be
System identification
Identify the response of an unknown system such as a communications channel or a telephone
8/12/2019 Dsp Lab Assignments
73/112
line. The filter adapts once, then stays fixed.
Inverse system identification
Develop a filter with a responsse that is the inverse of an unknown system. You can overcomeechoes in modem connections and local telephone lines by inserting an inverse adaptive filterand using it to compensate for the induced noise on the lines.
Noise cancellation
Perform active noise cancellation where the filter adapts in real time to keep the error small.Compare this to system identification.
Prediction
Predict a signals future values.
Adaptive Filters: Block Diagram
The block diagram below represents a general adaptive filter.
An adaptive FIR filter designs itself based on the characteristics of the input sinal and asignal that represents the desired behavior of the filter on the input. The filter does notrequire any other frequency response specifications. The filter uses an adaptive algorithmto reduce the error between the output signal y(n) and the desired signal d(n). Whenperormance criteria for e(n) have achieved their minimum values through the iterations of
8/12/2019 Dsp Lab Assignments
74/112
8/12/2019 Dsp Lab Assignments
75/112
8/12/2019 Dsp Lab Assignments
76/112
In a system identification application, the unknown system is placed in parallel with theadaptive filter.
In this case the same input x(n) feeds both the adaptive filter and the unkown system. Whene(n) is small, the adaptive filter 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 filter system to be used for system
identification.
Inverse System Identification
By placing the unknown system in series with an adaptive filter, the filter becomes the inverseof the unknown system when e(n) becomes small. The process requires a delay inserted in
the desired signald(n) path to keep the data at the summation synchronized and the systemcausal.
Without the delay element, the adapting algorithm tries to match the output y(n) from theadaptive filter to an input x(n) that has not yet reached the adaptive elements because ithas to pass through the unknown system. Including a delay equal to the delay caused bythe unknown system prevents this condition.
Plain old telephone systems (POTS) commonly use inverse system identification 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 filter that rolls off
at higher frequencies (or data rates). Adding an adaptive filter with a response that is theinverse of the wire response, and adapting in real time, compensates for the rolloff and otheranomalies, increasing the available frequency range and data rate for the telephone system.
Sketch the block diagram of an adaptive filter system to be used for inverse
system identification.
8/12/2019 Dsp Lab Assignments
77/112
Noise Cancellation
In noise cancellation, adaptive filters remove noise from a signal in real time. To do this, a
signal Z(n) correlated to the noise is fed to the adaptive filter.
As long as the input to the filter is correlated to the unwanted noise accompanying thedesired signal, the adaptive filter adjusts its coefficients to reduce the value of the differencebetween y(n) and d(n), removing the noise and resulting in a clean signal in e(n). Noticethat the error signal converges to the input data signal in this case, rather than convergingto zero.
Try:
edit babybeat
babybeat
Sketch the block diagram of an adaptive filter system to be used for system
identification.
Prediction
Predicting signals might seem to be an impossible task. Some limiting assumptions mustbe imposed by assuming that the signal isperiodic and either steady or slowly varying overtime.
Accepting these assumptions, an adaptive filter attempts to predict future values of thedesired signal based on past values. The signals(n) is delayed to create x(n), the input tothe adaptive filter. s(n) also drives the d(n) input. When s(n) is periodic and the filter islong 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 filter system to be used for system
identification.
Multirate Filters
Multirate filters alter the sample rate of the input signal during the filtering process. Theyare useful in both rate conversion and filter bank applications.
Like adaptive filters, multirate filters are implemented in the Filter Design Toolbox as mul-tirate filter (mfilt) objects. Again, this object-oriented approach to filtering involves twosteps:
8/12/2019 Dsp Lab Assignments
78/112
8/12/2019 Dsp Lab Assignments
79/112
E E 2 7 5 Lab June 30, 2006
Lab 7. Filter Implementation in Matlab
Introduction
This lab examines the process of moving from filter design to hardware implementation.The lab investigates various architectures and various quantization schemes, and discusseshardware description language (HDL) code generation.
Filter Architectures
After the filter design process has generated filter coefficients b and a, or a filter objecth (such as adaptfiltor mfilt object), the filter is implemented in a filter architectureusinglow-level operations of sum, gain, and delay (essentially, a block diagram of the differenceequation).
Approximately two dozen filter architectures are supported by Matlabs Signal Processingand 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