0% found this document useful (0 votes)
44 views

DSP Lab 10

This document provides instructions for designing digital filters, including both IIR and FIR filters, using MATLAB. It discusses estimating the order of IIR filters using functions like buttord, cheb1ord, and ellipord. It then covers designing IIR filters of different types (Butterworth, Chebyshev I, Chebyshev II, and elliptic) using commands like butter, cheby1, cheby2, and ellip. For FIR filter design, it describes windowing techniques using fir1 and arbitrarily shaped magnitude responses using fir2, as well as the optimal Parks-McClellan algorithm using firpm. The document includes an example of designing a Butterworth bandstop filter in MATLAB.

Uploaded by

Mo Rose
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

DSP Lab 10

This document provides instructions for designing digital filters, including both IIR and FIR filters, using MATLAB. It discusses estimating the order of IIR filters using functions like buttord, cheb1ord, and ellipord. It then covers designing IIR filters of different types (Butterworth, Chebyshev I, Chebyshev II, and elliptic) using commands like butter, cheby1, cheby2, and ellip. For FIR filter design, it describes windowing techniques using fir1 and arbitrarily shaped magnitude responses using fir2, as well as the optimal Parks-McClellan algorithm using firpm. The document includes an example of designing a Butterworth bandstop filter in MATLAB.

Uploaded by

Mo Rose
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

LAB No.

10
Digital Filter Design

Objective:
Theprocess ofderivingthetransfer functionG(z) whosefrequency response
G(ejw )approximatesthegivenfrequencyresponsespecificationsiscalleddigitalfilterdesign
.After G(z)hasbeenobtained, itisthenrealizedintheformofasuitablefilterstructure.Inthe
previouslaboratoryexercise,therealizationsofFIRandIIRtransferfunctions havebeen
considered.InthislaboratoryexerciseyouwilllearnhowtodesignanIIRorFIRdigital
filtertomeetaspecifiedmagnitudeorgainresponse.

IIR Filter Design


ThemostcommonmethodofIIRfilterdesignisbasedonthebilineartransformationof
aprototypeanalogtransferfunction. Theanalogtransferfunctionisusuallyoneofthe
followingtypes:Butterworth,Type1Chebyshev,Type2Chebyshev,andelliptic transfer
functions. Thedifferencebetweenthesefilter typescanbeexplainedbyconsideringthe
analoglowpassfilter.

TheButterworthlowpasstransferfunction hasamaximally-flat
magnituderesponseatdc,thatis,Ω=0,andamonotonicallydecreasingmagnitude
responsewithincreasingfrequency.
TheType1Chebyshevlowpasstransferfunctionhasan
equiripplemagnituderesponseinthepassbandandamonotonicallydecreasingmagnitude
responsewithincreasingfrequencyoutsidethe passband.
TheType2Chebyshevlowpass
transferfunctionhasamonotonicallydecreasingmagnituderesponseinthepassbandwith
increasingfrequencyandanequiripple magnitude responseinthestopband.
Finally,the
ellipticlowpasstransferfunctionhasequiripplemagnituderesponsesbothinthepassband
and inthestopband.

Project9.1 EstimationofOrderofIIRFilter
Thefirststepinthefilterdesignprocessis tochoosethetypeoffilterapproximationtobe
employedandthentoestimatetheorderofthetransferfunctionfromthefilterspecifications.
TheMATLABcommandforestimatingtheorderofaButterworthfilteris

[N, Wn]=buttord(Wp,Ws, Rp, Rs),

wheretheinputparametersarethenormalizedpassbandedgefrequencyWp,thenormaliz
ed stopbandedgefrequencyWs,thepassbandrippleRpindB,andtheminimumstopband
attenuationRsindB.BothWpandWsmustbeanumberbetween0and1withthesampling
frequencyassumedtobe2Hz.TheoutputdataarethelowestorderNmeetingthespecificati
onsandthe normalizedcutofffrequencyWn.IfRp=3
dB,thenWn=Wp.buttordcanalsobeusedtoestimatetheorderofahighpass,abandpass,an
dabandstopButterworth
filter.Forahighpassfilterdesign,Wp>Ws.Forbandpassandbandstopfilterdesigns,Wpand
Wsaretwo-element
vectorsspecifyingbothedgefrequencies,withtheloweredgefrequencybeingthefirstele
mentofthevector.Inthelattercases,Wnisalsoatwo-element vector.

ForestimatingtheorderofaType1Chebyshevfilter,theMATLABcommandis

[N, Wn]=cheb1ord(Wp,Ws, Rp, Rs)

andfordesigningaType2Chebyshevfilter,theMATLABcommand forestimating the


order is

[N, Wn]=cheb2ord(Wp,Ws, Rp, Rs).

Finally,inthecaseofanellipticfilterdesign,thecommandis

[N, Wn]=ellipord(Wp,Ws, Rp, Rs).

Asbefore,WpandWsarethepassbandandstopbandedgefrequencieswithvaluesbetween0
and1.Likewise,RpandRsarethepassbandrippleandtheminimumstopbandattenuation
indB.Ncontainstheestimated lowestorderandWnisthecutofffrequency.Itshouldbe
notedthatforbandpassandbandstopfilterdesigns,theactualorderofthetransferfunctio
n obtained usingtheappropriatefilterdesigncommandis2N.

Project9.2 IIRFilterDesign

Afterthefiltertypehasbeenselectedanditsorderestimatedthenext stepis todetermine


thetransferfunctionofthefilter.TothisendMATLABprovidesfunctionsforallfourtypes
of filters.FordesigningButterworthdigitallowpassorbandpassfilters,thecommandis
[num,den]=butter(N,Wn)

wheretheinputparametersNandWnaredeterminedthroughtheuseofthefunctionbuttor
d, andtheoutputisthevectorsnumanddencontaining,respectively,thecoefficientsofthe
numeratoranddenominator polynomials ofthetransferfunctioninascendingpowersof
z —1.IfWnisascalar,butterreturnsalowpasstransferfunctionoforderN,andifWnis
atwo-elementvector,itreturnsabandpass transferfunctionoforder2N.Fordesigning a
Butterworth digitalhighpassfilteroforderN, thecommandis

[num,den]=butter(N,Wn,’high’)

whereas,thecommand

[num,den]=butter(N,Wn,’stop’)

returnsthetransferfunction ofaButterworthbandstop filteroforder2NprovidedWnisa


two-element vector.FordesigningaType1Chebyshevdigitalfilter,thecommandsare

[num,den]=cheby1(N,Rp,Wn)
[num,den]=cheby1(N,Rp,Wn,’filtertype’)

FordesigningaType2Chebyshevdigitalfilter,thecommandsare

[num,den]=cheby2(N,Rs,Wn)
[num,den]=cheby2(N,Rs,Wn,’filtertype’)

Finally,fordesigninganellipticdigitalfilter,thecommandsare

[num,den]=ellip(N,Rp,Rs,Wn)
[num,den]=ellip(N,Rp,Rs,Wn,’filtertype’)

AlowpasstransferfunctionoforderN isreturnedineachcaseifWnisascalar,anda
bandpasstransferfunctionoforder 2NisreturnedifWnisatwo-elementvector.Ineachof
theabovecommands,filtertypeishighfordesigningahighpassfilterwithWnbeinga
scalar,andfiltertypeisstopfordesigningabandstopfilterwithWnbeingatwo-
element vector.

ProgramP9_1illustratesthedesignofaButterworthbandstopfilter.
% Program P7_1
% Design of a Butterworth Bandstop Digital Filter
clearall; close all; clc

Ws = [0.4 0.6]; Wp = [0.3 0.7]; Rp = 0.4; Rs = 50;


% Estimate the Filter Order
[N1, Wn1] = buttord(Wp, Ws, Rp, Rs);
% Design the Filter
[num,den] = butter(N1,Wn1,'stop');
% Program P7_1
% Design of a Butterworth Bandstop Digital Filter
Ws = [0.4 0.6]; Wp = [0.3 0.7]; Rp = 0.4; Rs = 50;
% Estimate the Filter Order
[N1, Wn1] = buttord(Wp, Ws, Rp, Rs);
% Design the Filter
[num,den] = butter(N1,Wn1,'stop');

FIR Filter Design


ConceptuallythesimplestapproachtoFIRfilter designistosimplytruncatetoafinite
numberoftermsthedoublyinfinite-
lengthimpulseresponsecoefficientsobtainedbycomputingtheinversediscrete-
timeFouriertransformofthedesiredidealfrequencyresponse.
However,asimpletruncationresultsinanoscillatorybehaviorintherespectivemagnitude
responseoftheFIRfilter,whichismorecommonlyreferredtoastheGibbsphenomenon.
TheGibbsphenomenoncanbereduced bywindowingthedoubly infinite-lengthimpulse
responsecoefficientsbyanappropriatefinite-lengthwindowfunction.Thefunctionsfir1
andfir2 canbeemployedtodesignwindowedFIRdigitalfiltersinMATLAB.Both functions
yieldalinear-phasedesign.
Thefunctionfir1canbeusedtodesignconventionallowpass,highpass,bandpass,and
bandstop linear-phaseFIRfilters.Thecommand

b =fir1(N,Wn)

returnsinvectorbtheimpulseresponsecoefficients, arrangedinascendingpowersofz —
1, ofalowpassorabandpassfilteroforderNforanassumedsamplingfrequencyof2Hz.
Forlowpassdesign,the normalizedcutofffrequencyisspecifiedby ascalarWn,anumber
between0and1.Forbandpassdesign,Wnisatwo-elementvector[Wn1, Wn2]containing
the specifiedpassbandedgeswhere0 <Wn1<Wn2<1.Thecommand

b =fir1(N,Wn,’high’)

withNaneveninteger,isusedfordesigningahighpassfilter.Thecommand

b =fir1(N,Wn,’stop’)
withWnatwo-elementvector,isemployedfordesigningabandstopFIRfilter.Ifnoneis
specified,theHammingwindowisemployedasadefault.Thecommand

b =fir1(N,Wn,taper)

makesuseofthespecifiedwindowcoefficientsoflengthN+1inthevectortaper.However,
thewindowcoefficients
mustbegeneratedaprioriusinganappropriateMATLABfunction suchasblackman,
hamming,hanning,chebwin, orkaiser.Thecommandstouseare of
thefollowingforms:

taper=blackman(N) taper =hamming(N) taper=hanning(N)


taper=chebwin(N) taper =kaiser(N,beta)

Thefunctionfir2canbeusedtodesignlinear-phaseFIRfilters witharbitrarilyshaped
magnitude responses.Initsbasicform,thecommandis

b =fir2(N,fpts,mval)

whichreturnsinthevectorboflengthN+1theimpulseresponsecoefficients,arrangedin
ascendingpowersofz —1. fptsisthevectorofspecifiedfrequencypoints,arrangedin
anincreasingorder,intherange0to1withthefirstfrequencypointbeing0andthelast
frequencypointbeing1.Asbefore,thesamplingfrequencyisassumedtobe2Hz.mvalis
avectorofspecifiedmagnitudevaluesatthespecifiedfrequencypointsandthereforemust
alsobeofthesame lengthasfpts.TheHammingwindow isused asadefault.Tomake use
ofotherwindows,thecommandtouseis

b =fir2(N,fpts,mval,taper)

where the vector taper contains the specified window coefficients.


A more widely used linear-phase FIR filter design is based on the Parks–
McClellan algorithm, which results in an optimal FIR filter with an equiripple
weighted error ε (w) defined in Eq. (9.1).
[ ]
E ( ω )=P ( ω ) |H ( e )|− D ( ω ) (9.1)

It makes use of the Remez optimization algorithm and is available in MATLAB as


the function firpm. This function can be used to design any type of single-band
or multiband filter, the differentiator, and the Hilbert transformer. In its basic
form, the command
b =firpm(N,fpts,mval)
returnsavectorboflengthN+1containingtheimpulseresponsecoefficientsofthedesired
FIRfilterinascendingpowersofz —1. fptsisthevectorofspecified frequencypoints,
arrangedinincreasingorder,intherange0to1withthefirstfrequencypointbeing0
andthelastfrequencypointbeing1.Asbefore,thesamplingfrequencyisassumedtobe 2Hz.
ThedesiredmagnitudesoftheFIRfilter frequencyresponseatthespecifiedband
edgesaregivenbythevectormval,withtheelements giveninequal-valuedpairs. The
desiredmagnitudesbetweentwospecifiedconsecutivefrequencypointsf(k)andf(k+1)
aredeterminedaccordingtothefollowingrules.Forkodd,themagnitudeisalinesegment
joiningthepoints{mval(k),fpts(k)}and{mval(k+1),fpts(k+1)},whereas,forkeve
n,itisunspecifiedwiththefrequencyrange[fpts(k),fpts(k+1)]beingatransition
or“don’tcare”region.Thevectorsfptsandmvalmustbeofthesamelengthwiththe
lengthbeingeven. Figure7.4illustratestherelationshipbetweenthevectorsfptsand
mvalgivenby

fpts=[00.20.40.70.81.0]
mval=[0.50.51.01.00.30.3]

FIGURE 9.1: ILLUSTRATION OF RELATIONSHIP BETWEEN VECTORS FPTS AND MVAL

Thedesiredmagnituderesponsesinthepassband(s)andthestopband(s)canbeweighted
byanadditionalvectorwgtsincludedastheargumentofthefunctionfirpm.Thefunction
canbe usedto designequirippleTypes1,2,3,and4linear-phaseFIRfilters.Types1and
2 arethedefaultdesignsfororderNeven andodd,respectively.Types 3 (Neven) and4 (N
odd)areusedforspecializedfilterdesigns,theHilberttransformerandthedifferentiator.
TodesignthesetwotypesofFIRfiltersthefiagshilbertand differentiatorareused
forftypeinthelasttwoversionsoffirpm.Thecommand

b =firpm(N,fpts,mval,wgts)
isusedto designan FIRfilterweightedin eachbandby the elementsof the weight vector
wgtswhoselengthisthushalfthatoffpts.Theelementsofthevectorwgtscanbe
determinedfromthespecified passbandandstopbandripplesbydividingthemaximum
ripplevaluebytheripplevalues.TodesignaHilberttransformeroradifferentiator,usethe
forms

firpm(N,fpts,mval,ftype)
firpm(N,fpts,mval,wgts,ftype)

whereftypeisthestringhilbertordifferentiator.InthecaseofaHilberttransfor
mer design,thesmallestelementinfptsshouldnotbea0.

TheorderNoftheFIRfiltertomeetthegiven specificationscanbeestimatedusingeither
Kaiser’sformulaofEq.(9.2).

−20 log 10 ( √ δ p δ s )−13


N≅ (9.2)
14.6 ( Δω ) /2 π

The MATLABfunction kaiordgivenbelowimplementsKaiser’sformula:

function N = kaiord(Fp, Fs, dp, ds, FT)


% Computation of the length of a linear-phase
% FIR multiband filter using Kaiser’s formula
% dp is the passband ripple
% ds is the stopband ripple
% Fp is the passband edge in Hz
% Fs is the stopband edge in Hz
% FT is the sampling frequency in Hz.
% If none specified default value is 2
% N is the estimated FIR filter order
ifnargin == 4,
F T=2 ;
end
if length(Fp) > 1,
TBW = min(abs(Fp(1) - Fs(1)), abs(Fp(2) - Fs(2)));
else
TBW = abs(Fp - Fs);
end
num = -20*log10(sqrt(dp*ds)) - 13;
den = 14.6*TBW/FT;
N = ceil(num/den);

ThefunctionkaiserordintheSignalProcessingToolboxcanalsobeusedforestimating the
filterorderusingKaiser’sformula.Itcanbeusedinoneofthefollowingforms:
[N, Wn,beta,ftype]=kaiserord(fedge,aval, dev)
[N, Wn,beta,ftype]=kaiserord(fedge,aval, dev,FT)
c =kaiserord(fedge,aval, dev,FT, ’cell’)

whereFTisthesamplingfrequencyinHzwhosedefaultvalueis2Hzifnotspecified; fedgeisa
vectorofbandedgefrequenciesinHz,inincreasingorderbetween0andFT/2;
andavalisavectorspecifyingthedesiredvaluesofthemagnituderesponseatthespecified
bandedgesgivenbyfedge.Thelengthoffedgeis2lessthantwicethelengthofavaland
therefore mustbeeven.devisavectorofmaximumdeviationsorripplesindBallowable
foreachband.Ifthedeviationsspecifiedareunequal,thesmallestoneisusedforallbands.
Theoutputdataareinthedesiredformatforuseinfir1,withnormalizedbandedgesWnandth
eparameterbetausedforcomputingthewindowcoefficientsasgiveninEq.(7.36).
Thestringftypespecifiesthefiltertypeforfir1.Itishighforhighpassfilterdesign,and
stopforbandstopfilterdesign.Thelastform ofkaiserordspecifiesacellarray whose
elements areparameterstofir1.
TheMATLABfunctionfirpmordimplementstheformulaofEq.(7.8).It canbeusedin one
ofthefollowingforms:

[N,fts,mval,wgts]=firpmord(fedge,aval,dev)
[N,fts,mval,wgts]=firpmord(fedge,aval,dev,FT)

whereFTisthesamplingfrequencyinHzwhosedefaultvalueis2Hzifnotspecified,
fedgeisa vectorofbandedgefrequenciesinHz,inincreasingorderbetween0andFT/2;
andavalisavectorspecifyingthedesiredvaluesofthemagnituderesponseatthespecified
bandedgesgivenbyfedge.Thelengthoffedgeis2lessthantwicethelengthofavaland
therefore mustbeeven.devisavectorofmaximumdeviationsorripplesindBallowable
for eachband.Athirdformoffirpmordisgivenby

c =firpmord(fedge,aval,dev,FT,’cell’)

and specifies a cell array whose elements are the parameters to firpm.

In some cases, the order N determined using either method may not result in an FIR
filter meeting the original specifications. If it does not, the order should either be
increased or decreased by 1 gradually until the specifications are met. Moreover,
the order estimates may be highly inaccurate for very narrowband or very
wideband FIR filters.

LabTasks

1. Using MATLAB determine the lowest order of a digital IIR low pass filter of all
four types. The specifications are as follows: sampling rate of 40kHz, pass
band edge frequency of 4kHz, stop band edge frequency of 8kHz, passband
ripple of 0.5dB ,and a minimum stop band attenuation of 40dB.Comment on
your results.
Ans:

Using these values and buttord we get the lowest order for a Butterworth lowpass
filter to be – the correct call is [N, Wn] = buttord(0.2,0.4,0.5,40). This gives
N=8. The corresponding normalized passband edge frequency Wn is - 0.2469, or
0.2469

2. Using MATLAB determine the lowest order of a digital IIR high pass filter of all
four types. The specifications are as follows: sampling rate of 3,500Hz, pass
band edge frequency of 1,050Hz, stop band edge frequency of 600Hz, pass
band rippleof1dB, and a minimum stop band attenuation of 50dB.Comment on
your results.
Ans:

Using these values and buttord we get the lowest order for a Butterworth highpass
filter to be – the correct call is [N, Wn] = buttord(Wp,Ws,Rp,Rs). This gives
N=8. The corresponding normalized passband edge frequency Wn is – Wn = 0.5646.
3. UsingMATLABdeterminethelowestorderofadigitalIIRbandpassfilterofallfour
types.Thespecificationsareasfollows:samplingrateof7kHz, pass band edge
frequencies at 1.4kHz and 2.1kHz ,stop band edge frequencies at 1.05kHz and
2.45kHz, pass band ripple of 0.4dB ,and a minimum stop band attenuation of
50dB. Comment on your results.
Ans:

The desired passband ripple Rp is – 0.4 dB.


The desired stopband ripple Rs is – 50 dB.
Using these values and buttord we get the lowest order for a Butterworth bandpass
filter to be – the correct call is [N,Wn] = buttord(Wp,Ws,Rp,Rs) = buttord([0.4000
0.6000],[0.3000 0.7000],0.4,50), which gives Order = 2N = 18
4. Using MATLAB determine the lowest order of a digital IIR band stop filter of
all four types. The specifications are as follows: samplingrateof12kHz,pass
band edge frequencies at 2.1kHz and 4.5kHz, stop band edge frequencies
at2.7kHz and 3.9 kHz, pass band ripple of 0.6dB, and a minimum stop band
attenuation of45dB.Commenton your results.

Using these values and buttord we get the lowest order for a Butterworth bandstop
filter to be – the correct call is [N,Wn] = buttord(Wp,Ws,Rp,Rs) = buttord([0.3500
0.7500],[0.4500 0.6500],0.6,45), which gives Order = 2N = 18
5. Design the Butterworth band stop filter by running ProgramP9_1. Write down
the exact expression for the transfer function generated. Whatarethefilter
specifications? Does your design meet the specifications? Using MATLAB,
compute and plot the filter’s unwrapped phase response and the group delay
response.
Ans:

6. Modify ProgramP9_1 to design a Type1 Chebyshev low pass filter meeting the
given specifications of Question Q 1. Write down the exact expression for the
transfer function generated. Does your design meet the specifications? Using
MATLAB, compute and plot the filter’s unwrapped phase response and the
group delay response.
Ans:

7. Modify ProgramP9_1 to design a Type2 Chebyshev high pass filter meeting the
specifications given in Question Q 2. Write down the exact expression for the
transfer function generated. Does your design meet the specifications? Using
MATLAB, compute and plot the filter’s unwrapped phase response and the
group delay response.
Ans:
8. Modify ProgramP9_1 to design an elliptic band pass filter meeting the
specifications given in Question Q 3.Write down the exact expression for the
transfer function generated. Does your design meet the specifications ?Using
MATLAB, compute and plot the filter’s unwrapped phase response and the
group delay response.
Ans:
9. Using the function kaiord, estimate the order of a linear-phase lowpass FIR
filter with the following specifications: pass band edge=2kHz, stop band
edge=2.5kHz, pass band ripple δp =0.005, stop band ripple δS=0.005, and
sampling rate of 10kHz. What are the purposes of the commands ceil and
nargin in the function kaiord?
Ans:
The estimated order of a linear-phase lowpass FIR filter with the following
specifications: ωp = 2 kHz, ωs = 2.5 kHz, δp = 0.005, δs = 0.005, and FT = 10 kHz
obtained using kaiord is – N = 46. The correct call is
kaiord(2000,2500,0.005,0.005,10000).
The purpose of the command ceil is – To round the estimated order up to the next
largest integer; the order has to be integer, so if the formula returns a fraction it
needs to be rounded up to the next whole number. The purpose of the command
nargin is to detect if kaiord has been called with four arguments or with five. If five,
it’s assumed that all the frequencies are analog and that the last argument is the
sampling frequency. If four, then the sampling frequency defaults to 2, implying that
the other frequency arguments are in units of cycles per sample.

You might also like