E E 2 7 5 Lab

June 30, 2006

FIR Filters in Matlab
Digital ﬁlters with ﬁnite-duration impulse reponse (all-zero, or FIR ﬁlters) have both advantages and disadvantages when compared to inﬁnite-duration impulse response (IIR) ﬁlters. FIR ﬁlters have the following primary advantages: • They can have exactly linear phase. • They are always stable, even when quantized. • The design methods are generally linear. • They can be realized eﬃciently in hardware. • The ﬁlter startup transients have ﬁnite duration. The primary disadvantage of FIR ﬁlters is that they often require a much higher ﬁlter order than IIR ﬁlters to achieve a given level of performance. Correspondingly, the delay of these ﬁlters is often much greater than for an equal performance IIR ﬁlter.

FIR Methods
The Signal Processing Toolbox supports a variety of methods for the design of FIR ﬁlters. F ilterM ethod Windowing Multiband with Transition Bands Constrained Least Squares Arbitrary Response Raised Cosine Description Apply window to truncated inverse Fourier transform of desired ﬁlter Equiripple or least squares approach over frequency subbands Minimize squared integral error over entire frequency range subject to maximum error constraints Arbitrary responses, including nonlinear phase and complex ﬁlters Lowpass response with smooth, sinusoidal transition c 2006GM F ilterF unctions ﬁr1, ﬁr2, kaiserord ﬁrls, ﬁrpm, ﬁrpmord ﬁrcls, ﬁrcls1

cﬁrpm ﬁrrcos

The FIR ﬁlter coeﬃcients give the impulse response. Try this: b = [-1 0 2 -3 1]. .Impulse Response Revisited FIR ﬁlters are described by diﬀerence equations of the form M y(n) = m=0 bm x(n − m) where the ﬁltered signal y(n) is just a linear combination of current and previous values of the input signal x(n). The denominator of the transfer function will always be a = 1. impz(b.1) Why are the x-axis scales diﬀerent? Linear Phase Filters A ﬁlter whose impulse response is symmetric about its midpoint is called a (generalized) linear phase ﬁlter. The order of the ﬁlter is n = length(b) − 1. • The magnitude of the DFT is scaled by the ﬁlter’s magnitude response (there is no amplitude distortion).etc.. The coeﬃcients b are the numerator coeﬃcients of the transfer function. % no need to specify the a coefficients stem(b) figure..]. For an order n linear phase FIR ﬁlter. • The phase shift φ of a ﬁltered signal will vary linearly with frequency ω (pure time delay with no phase distortion).. the phase delay and group delay is n/2. • The DFT of the impulse response will be either purely real or purely imaginary. For such ﬁlters. • The phase delay −φ(ω)/ω and group delay −dφ(ω)/d(ω) will be equal and constant. If the input signal is the unit impulse x = [1 0 0 0 . then the corresponding impulse response y(n) = h(n) is identical to b(n): h(0) = b0 x(0) = b0 h(1) = b0 x(1) + b1 x(0) = b1 h(2) = b0 x(2) + b1 x(1) + b2 x(0) = b2 ..

The absence of either amplitude distortion or phase distortion preserves the waveform of signals in the passband. even symmetry Even length. . n + 1 H(0) = 0 b(k) = −b(n + 2 − k).0. n + 1 No restriction b(k) = b(n + 2 − k). n + 1 H(0) = 0 Symmetry ResponseH(1) No restriction H(1) = 0 H(1) = 0 No restriction The functions ﬁr1.. Try: a = 1.5)... .. k = 1. Except for cﬁrpm. ﬁrcls.. odd symmetry Depending on the ﬁlter type. FIR Filter Types The symmetric impulse response of a linear phase ﬁlter can have an odd or an even number of points. . odd symmetry Even length.. The function cﬁrpm can design any type of linear or nonlinear phase ﬁlter. fvtool(b. all the FIR ﬁlter design functions in the Signal Processing Toolbox design linear phase ﬁlters only. Both ﬁrls and ﬁrpm design type III and IV linear phase FIR ﬁlters given a ’hilbert’ or ’diﬀerentiator’ ﬂag. certain restrictions apply: F ilter T ype Type I Type II Type III Type IV F ilter Order Even Odd Even Odd ResponseH(0) (N yquist) b(k) = b(n + 2 − k). ﬁrls. k = 1. ﬁrcls1... . n + 1 No restriction b(k) = −b(n + 2 − k). and ﬁrrcos all design type I and II linear phase FIR ﬁlters by default. even symmetry Odd length. k = 1.. leading to four ﬁlter types: • • • • Type Type Type Type I: II: III: IV: Odd length. b = fir1(5. k = 1. ﬁrpm. . ﬁr2...and can have an odd or even symmetry about the midpoint.a) Look at the phase delay and the group delay..

For odd-valued n in these cases. the abrupt truncation leads to overshoot (Gibb’s phenomenon) and ripples in the spectrum. The approximation to the ideal ﬁlter is “best” in a mean square sense. • h(n) is symmetrically truncated (multiplied by a ﬁnite. Windowing does not explicitly impose amplitude response constraints. However. Window-Based Design Windowing is a common design method for FIR ﬁlters. The undesirable eﬀects of truncation are reduced or eliminated by the use of tapered windows. ﬁr1 does not design type II highpass and bandstop ﬁlters. compared to other approximations of the same length. symmetric window) to create a linear phase ﬁnite impulse response. Typing help window provides a list of available functions: . such as passband ripple or stopband attenuation. by Parseval’s theorem. • The corresponding ideal impulse response h(n) is determined by the inverse Fourier transform. this response cannot be implemented in a digital ﬁlter because it is inﬁnite and noncausal. In general.Because the frequency response of a type II ﬁlter is zero at the Nyquist frequency (“high” frequency). 50. ﬁr1 adds 1 to the order and returns a type I ﬁlter. 100) specify? How does the ﬁlter change with the argument? Windowing Functions The Signal Processing Toolbox supports a variety of windows commonly used in FIR ﬁlter design. • The ideal frequency response H(f ) is sampled. In this method. It must be used iteratively to produce designs that meet such speciﬁcations. Try: edit windemo windemo(20) windemo(50) windemo(100) What do the arguments (20.

64.’m’) . figure. w = gausswin(64.alpha) and w = window(@gausswin.w) n=linspace(0.bartlett barthannwin blackman blackmanharris bohmanwin chebwin flattopwin gausswin hamming hann kaiser nuttallwin parzenwin rectwin triang tukeywin Bartlett window Modiﬁed Bartlett-Hanning window Blackman window Minimum 4-term Blackman-Harris window Bohman window Chebyshev window Flat Top window Gaussian window Hamming window Hann window Kaiser window Nuttall deﬁned minimum 4-term Blackman-Harris window Parzen (de la Valle-Poussin) window Rectangular window Triangular window Tukey window Individual functions take inputs for a window length n and window parameters and return the window w in a column vector of length n. stem(n. wy=w’.alpha) both return a Gaussian window of length 64 with standard deviation equal to 1/alpha.3). Try: help window n=15. figure.wy. w=gausswin(n.*y. w=W(length(y)+1:end).6*pi.100). stem(n. stem(-7:7. y=sinc(n).y) W=gausswin(2*length(y).) The window function serves as a gateway to the individual functions. (Note: Use w’ for array products with row vector impulse responses.3).

By windowing the truncated signal in the time domain.5 0. Try: edit windft windft Tuncated signal and DFT: Truncated Signal 1 0.4 0.Explain the y and wy plots. high-frequency components are introduced that are visible in the DFT. endpoints are assigned a reduced weight.2 0.1 0.7 0. windowed signal and DFT: .8 0. but increase the width of the main lobe. Windowing and Spectra When a signal is truncated.3 0.5 0 −0. The eﬀect on the DFT is to reduce the height of the side lobes.5 −1 0 0.6 0.9 1 DFT of Truncated Signal 50 40 Magnitude 30 20 10 0 0 1 2 3 4 5 6 7 8 9 10 Tuncated.

Windowed Signal 1 0. which can be any window in the Signal Processing Toolbox.3 0. Ideally. .7 0.8 0. The main lobe should be as narrow as possible and the side lobes should contain as little energy as possible. Several windows can be given as input arguments for comparative display.2 0. adjustable by changing the ﬁlter order. wvtool(windowname(n)) opens WVTool with time and frequency domain plots of the n-length window speciﬁed in windowname. Windowed Signal 25 20 Magnitude 15 10 5 0 0 1 2 3 4 5 6 7 8 9 10 Window Visualization Tool The transition bandwidth of a window-based FIR ﬁlter is determined by the width of the main lobe of the DFT of the window function.4 0.6 0. The Window Visualization Tool (WVTool) allows you to investigate the tradeoﬀs among diﬀerent windows and ﬁlter orders. The actual approximation error is scaled by the amount of the passband magnitude response. Passband and stopband ripples are determined by the magnitude of the side lobe of the DFT of the window function.9 1 DFT of Truncated. and are usually not adjustable by changing the ﬁlter order. the spectrum of a window should approximate an impulse.1 0.Truncated.5 0.5 −1 0 0.5 0 −0.

For example. Some windows are combinations of simpler windows. The Hamming window minimizes side lobe peaks (at the expense of slower high-frequency decay). the Hann window is the sum of a rectangular and a cosine window. Can you think of an advantage one would have over the other? . Other windows are based on simple mathematical formulas for easy application.Try: wvtool(hamming(32). The Kaiser window has a parameter that can be tuned to control side lobe levels. wintool opens WinTool with a default 64-point Hamming window.experiment with diﬀerent window designs and export them to the workspace. The Hann window is easy to use as a convolution in the frequency domain. • Use WinTool to interactively design windows with certain speciﬁcations and export them to the Matlab workspace. • Use WVTool for displaying and comparing existing windows created in the Matlab workspace. Most window types satisfy some optimality criterion. the Kaiser window gives the best approximation to such an optimal window.2. Try it . The Hann window improves high-frequency decay (at the expense of larger peaks in the side lobes). In the discrete domain. An optimal time-limited window maximizes energy in its spectrum over a given frequency band.kaiser(32.5).1). Comment on the Chebyshev compared to the Blackman-Harris window.kaiser(32.5).flattopwin(32)) wvtool(kaiser(32. Other windows emphasize certain desirable features.kaiser(32.10)) Window Design and Analysis Tool The Window Design and Analysis Tool (WinTool) is used in conjunction with the Window Visualization Tool. and the Bartlett window is the convolution of two rectangular windows.

4*(-25:25)). type fvtool(b. but a nonrectangular window reduces its magnitude. The window applied here is a simple rectangular window. This is at the expense of transition width (the windowed version takes longer to ramp from passband to stopband) and optimality (the windowed version does not minimize the integrated least squared error).4*sinc(0. fvtool(b. To display the ﬁlter’s frequency response in FVTool. digital low-pass ﬁlter with a cutoﬀ frequency of ω0 rad/s.*hamming(51)’. Its impulse response sequence h(n) is 1 2π π −π H(ω)ejωn dω = 1 2π ω0 −ω0 ejωn dω = ω0 ω0 sinc n π π This ﬁlter is not implementable since its impulse response is inﬁnite and noncausal. This “Gibb’s effect” does not vanish as the ﬁlter length increases. in the integrated least squares sense.*hamming(51)’. a length 51 ﬁlter with a lowpass cutoﬀ frequency ω0 of 0. and magnitude 0 at frequencies between ω0 and π. Try: b=0.1) Ringing and ripples occur in the response. especially near the band edge. turncate it by applying a window. fvtool(bw.1) Using a Hamming window greatly reduces the ringing. Multiplication by a window in the time domain causes a convolution or smoothing in the frequency domain.4π rad/s is b=0. fvtool(b.Example: Lowpass Filter Consider the ideal.1) Right-click the y-axis label in FVTool and choose Magnitude squared on both plots. Retain the central section of impulse response in the turncation to obtain a linear phase FIR ﬁlter. For example.4*(-25:25)). By Parseval’s theorem. or “brick wall”.1) bw=b. This ﬁlter has magnitude 1 at all frequencies less than ω0 . To create a ﬁnite-duration impulse response. this is the length 51 ﬁlter that best approximates the ideal lowpass ﬁlter. Apply a length 51 Hamming window to the ﬁlter and display the result using FVTool: bw=b. .4*sinc(0.

If you do not specify a window. The commands n=50. The vector window must be n + 1 elements long. b=fir1(n. For a highpass ﬁlter. Given a ﬁlter order and a description of an ideal ﬁlter. ﬁr1 applies a Hamming window. create a row vector b containing the coeﬃcients of the order n Hamming-windowed ﬁlter. but they accept any windowing function. and bandstop. Both use Hamming windows by default. uses the window speciﬁed in column vector window for the design. The kaiserord function estimates the ﬁlter order.window). kaiserord returns appropriate input parameters for the ﬁr1 function.Wn. Wn=0. half the sampling frequency. linear phase FIR ﬁlter with cutoﬀ frequency W n. and a maximum allowable ripple.Where in the plot is the ringing reduced by the window? Standard Band FIR Design The Signal Processing Toolbox functions ﬁr1 and ﬁr2 are both based on the windowing method.Wn). bandpass. This is a lowpass. cutoﬀ frequency. where 1 corresponds to the Nyquist frequency. Try: edit fir1demo fir1demo Exercise . W n is a number between 0 and 1. a vector of magnitude. b=fir1(n. append the string ’stop’ for the bandstop conﬁguration. Given a vector of frequency band edges. these functions return a windowed inverse Fourier transform of the ideal ﬁlter. ﬁr1 resembles the IIR ﬁlter design functions in that it is formulated to design ﬁlters in standard band conﬁgurations: lowpass. simply append the string ’high’ to the function’s parameter list. For a bandpass or bandstop ﬁlter.4. and Kaiser window β parameter needed to meet a given set of speciﬁcations. specify Wn as a two-element vector containing the passband edge frequencies. highpass.

4. Arbitrary Response FIR Filters The ﬁr2 function also designs windowed FIR ﬁlters. The vector window must be n + 1 elements long. Try: edit directstop2 directstop2(10) directstop2(100) directstop2(500) edit nlinphase nlinphase . Filter the signal y with the designed ﬁlter. 3. The function cﬁrpm is used to design complex and nonlinear-phase equiripple FIR ﬁlters. (The IIR counterpart of this function is yulewalk). Compare signals and spectra before and after ﬁltering.f. Use a sampling frequency of 8192 Hz. ﬁr2 applies a Hamming window. The frequencymagnitude characteristics of this ﬁlter match those given by vectors f and m.1. b=fir2(n. Plot the response. 2. If you do not specify a window. b=fir2(n. uses the window speciﬁed in column vector window for the design. returns row vector b containing the n + 1 coeﬃcients of an order n FIR ﬁlter.m. Design a windowed FIR bandstop ﬁlter to remove the 300 Hz component from the threetone signal with noise y from Lab IIR Filters in Matlab.f.m).window). It allows arbitrary frequency-domain constraints. but with an arbitrarily shaped piecewise linear frequency response.

integrated squared error between an ideal piecewise linear function and the magnitude response of the ﬁlter over a set of desired frequency bands. b=firls(n. n 2 sinc 1 − (2R ns ) ns 0≤R≤1 R is called the rolloﬀ factor. which is the impulse response of an ideal lowpass ﬁlter. The function ﬁrls allows you to introduce constraints by deﬁning upper and lower bounds for the frequency response in each band. forms the basis for several other interpolating functions of the form n . where f (0) = 1 ns One commonly-used form is the raised cosine function: h(n) = f (n)sinc hrc (n) = n cos(πR ns ) n . The function ﬁrcls1 is used speciﬁcally to design lowpass and highpass linear phase FIR ﬁlters using constrained least squares. Try: edit firlsdemo firlsdemo edit firclsdemo firclsdemo Raised Cosine Filters The sinc function. This results in .Multiband Filters The function ﬁrls designs linear-phase FIR ﬁlters that minimize the weighted. Like the sinc function.a) returns row vector b containing the n+1 coeﬃcients of the order n FIR ﬁlter whose frequencyamplitude characteristics approximately match those given by vectors f and a. the raised cosine function is 1 at n = 0 and 0 at all other sampling instances n = ns . In contrast to the sinc function.f. the raised cosine has faster decaying oscillations on either side of the origin for R > 0.

improved reconstruction if samples are not acquired at exactly the sampling instants (i. and return an order n lowpass linear-phase FIR ﬁlter with a raised cosine transition band. The partial convolutions of the signal are returned to the time domain with the IFFT. r must be in the range [0. b=firrcos(n.F0.’rolloff’) interprets the third argument.25. Try: b = firrcos(20. freqz(b) Describe what you see.fs.’bandwidth’) are equivalent. all in hertz. Frequency Domain Filtering Often. The ﬁlter coeﬃcients (impulse response) and each block of data are transformed to the frequency domain using the FFT. 1]. an input signal x(n) is partitioned into equal length data blocks. df . It also uses fewer past and future values in the reconstruction.. as compared to the sinc function. where they can be eﬃciently convolved using multiplication. and total attenuation at high frequencies. as the rolloﬀ factor instead of the transition bandwidth.e. In the overlap-add method. b=firrcos(n. if there is jitter). The width of the transition band is determined by the rolloﬀ factor.df.fs) b=firrcos(n. . b is normalized so that the nominal passband gain is always equal to 1. The cutoﬀ frequency is F 0. a raised cosine function in the middle.0.F0. and the processed result constructed from the processed pieces.0.F0.fs. and sampling frequency is f s. df must be small enough so that F 0 ± df /2 is between 0 and f s/2. r. where they are shifted and summed using superposition.df. The shape of the function’s spectrum is the “raised cosine”. a long (perhaps continuous) stream of data must be processed by a system with only a ﬁnite length buﬀer for storage. The data must be processed in pieces. The ideal raised cosine lowpass ﬁlter frequency response consists of unity gain at low frequencies.r.2). the transition bandwidth df .25.

3). y=conv(h. y1=conv(h. edit filttimes filttimes Above what order can you say that ﬀtﬁlt 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”.x) uses an FFT length of nﬀt = 2nextpow2(n) and a data block length of nﬀt-length (b)+1 (ensures circular convolution). y=fftfilt(b. ﬁrﬁlt incurs an “oﬄine” startup cost when converting the coeﬃcients b to the frequency domain. zeros(1. ﬀtﬁlt outperforms ﬁlter. After that.x1) y2=conv(h. Y=Y1+Y2 Describe what is happening in this code.x) x1=[1 2 3]. 2006.) c 2006GM . Try: x=[1 2 3 4 5 6].x2) Y1=[y1. h=[1 1 1].3)]. (Multiplications are a good measure of performance.ﬀtﬁlt implements the overlap-add method for FIR ﬁlters. x2=[4 5 6]. The following script takes a few moments to run. Y2=[zeros(1. since they are typically expensive on hardware.) The net result is that for ﬁlters of high order.y2]. the number of multiplications ﬀtﬁlt performs relative to ﬁlter (which implements the ﬁlter in direct form) is ≈ log2 (L)/N . where L is the block length and N is the ﬁlter length.