Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Biosignal and Biomedical Image Processing MATLAB based Applications - John L. Semmlow

4.43 Mб

high frequency components. The result of applying this filter to the EEG signal is shown in Figure 4.11.

%Example 4.3 and Figures 4.10 and 4.11

%Application of an FIR bandpass filter based

%on a rectangular window design as shown in Figure 4.7

close all; clear all;

N =


% Number of data points

fs =


% Sample frequency

load sig_2;

% Get data

FIGURE 4.11 A segment of unfiltered EEG data (upper trace) and the bandpass filtered version (lower trace). A frequency response of the FIR bandpass filter is given in Figure 4.10.

Copyright 2004 by Marcel Dekker, Inc. All Rights Reserved.

wh =

.3 * pi;

% Set bandpass cutoff





wl =




L =


% Number of coeffients




equals 128

for i = 1:L 1

% Generate bandpass




coefficient function

n = i-L/2 ;


and make symmetrical

if n == 0



bn(i) = wh/pi-wl/pi;




bn(i) = (sin(wh*n))/(pi*n)-(sin(wl*n))/(pi*n) ;



% Filter impulse response








bn =

bn .* blackman(L 1)’;

% Apply Blackman window




to filter coeffs.

H_data = abs(fft(data));

% Plot data spectrum for





freq = (1:N/2)*fs/N;

% Frequency vector for






% Plot data FFT only to





hold on;







H =


% Find the filter




frequency response

H =

H*1.2 * (max(H_data)/max(H)); % Scale filter H(z) for






% Plot the filter




frequency response

xlabel(’Frequency (Hz)’); ylabel(’H(f)’);

y =


% Filter the data using








t =


% Time vector for






plot(t(1:N/2),data(1:N/2),’k’) % Plot only 1/2 of the % data set for clarity

xlabel(’Time (sec)’) ;ylabel(’EEG’); subplot(2,1,2); % Plot the bandpass

% filtered data

plot (t(1:N/2), y(1:N/2),’k’); ylabel(’Time’); ylabel(’Filtered EEG’);

Copyright 2004 by Marcel Dekker, Inc. All Rights Reserved.

In this example, the initial loop constructs the filter weights based on Eq. (12). The filter has high and low cutoff frequencies of 0.1π and 0.3 π radians/ sample, or 0.1fs/2 and 0.3fs/2 Hz. Assuming a sampling frequency of 100 Hz this would correspond to cutoff frequencies of 5 to 15 Hz. The FFT is also used to evaluate the filter’s frequency response. In this case the coefficient function is zero-padded to 1000 points both to improve the appearance of the frequency response curve and to match the data length. A frequency vector is constructed to plot the correct frequency range based on a sampling frequency of 100 Hz. The bandpass filter is applied to the data using convolution. Two adjustments must be made when using convolution to implement an FIR filter. If the filter weighting function is asymmetrical, as with the two-point central difference algorithm, then the filter order should be reversed to compensate for the way in which convolution applies the weights. In all applications, the MATLAB convolution routine generates additional points (N = length(data) + length(b(n) − 1) so the output must be shortened to N points. Here the initial N points are taken, but other strategies are mentioned in Chapter 2. In this example, only the first half of the data set is plotted in Figure 4.11 to improve clarity.

Comparing the unfiltered and filtered data in Figure 4.11, note the substantial differences in appearance despite the fact that only a small potion of the signal’s spectrum is attenuated. Particularly apparent is the enhancement of the oscillatory component due to the suppression of the lower frequencies. This figure shows that even a moderate amount of filtering can significantly alter the appearance of the data. Also note the 50 msec initial transient and subsequent phase shift in the filtered data. This could be corrected by shifting the filtered data the appropriate number of sample points to the left.


The primary advantage of IIR filters over FIR filters is that they can usually meet a specific frequency criterion, such as a cutoff sharpness or slope, with a much lower filter order (i.e., a lower number of filter coefficients). The transfer function of IIR filters includes both numerator and denominator terms (Eq. (4)) unlike FIR filters which have only a numerator. The basic equation for the IIR filter is the same as that for any general linear process shown in Eq. (6) and repeated here with modified limits:




y(k) = b(n) x(k n) − a(n) y(k n)





where b(n) is the numerator coefficients also found in FIR filters, a(n) is the denominator coefficients, x(n) is the input, and y(n) the output. While the b(n) coefficients operate only on values of the input, x(n), the a(n) coefficients oper-

Copyright 2004 by Marcel Dekker, Inc. All Rights Reserved.

ate on passed values of the output, y(n) and are, therefore, sometimes referred to as recursive coefficients.

The major disadvantage of IIR filters is that they have nonlinear phase characteristics. However if the filtering is done on a data sequence that totally resides in computer memory, as is often the case, than so-called noncausal techniques can be used to produce zero phase filters. Noncausal techniques use both future as well as past data samples to eliminate phase shift irregularities. (Since these techniques use future data samples the entire waveform must be available in memory.) The two-point central difference algorithm with a positive skip factor is a noncausal filter. The Signal Processing Toolbox routine filtfilt described in the next section utilizes these noncausal methods to implement IIR (or FIR) filters with no phase distortion.

The design of IIR filters is not as straightforward as FIR filters; however, the MATLAB Signal Processing Toolbox provides a number of advanced routines to assist in this process. Since IIR filters have transfer functions that are the same as a general linear process having both poles and zeros, many of the concepts of analog filter design can be used with these filters. One of the most basic of these is the relationship between the number of poles and the slope, or rolloff of the filter beyond the cutoff frequency. As mentioned in Chapter 1, the asymptotic downward slope of a filter increases by 20 db/decade for each filter pole, or filter order. Determining the number of poles required in an IIR filter given the desired attenuation characteristic is a straightforward process.

Another similarity between analog and IIR digital filters is that all of the well-known analog filter types can be duplicated as IIR filters. Specifically the Butterworth, Chebyshev Type I and II, and elliptic (or Cauer) designs can be implemented as IIR digital filters and are supported in the MATLAB Signal Processing Toolbox. As noted in Chapter 1, Butterworth filters provide a frequency response that is maximally flat in the passband and monotonic overall. To achieve this characteristic, Butterworth filters sacrifice rolloff steepness; hence, the Butterworth filter will have a less sharp initial attenuation characteristic than other filters. The Chebyshev Type I filters feature faster rolloff than Butterworth filters, but have ripple in the passband. Chebyshev Type II filters have ripple only in the stopband and a monotonic passband, but they do not rolloff as sharply as Type I. The ripple produced by Chebyshev filters is termed equi-ripple since it is of constant amplitude across all frequencies. Finally, elliptic filters have steeper rolloff than any of the above, but have equi-ripple in both the passband and stopband. In general, elliptic filters meet a given performance specification with the lowest required filter order.

Implementation of IIR filters can be achieved using the filter function described above. Design of IIR filters is greatly facilitated by the Signal Processing Toolbox as described below. This Toolbox can also be used to design FIR filters, but is not essential in implementing these filters. However, when filter

Copyright 2004 by Marcel Dekker, Inc. All Rights Reserved.

requirements call for complex spectral characteristics, the use of the Signal Processing Toolbox is of considerable value, irrespective of the filter type. The design of FIR filters using this Toolbox will be covered first, followed by IIR filter design.


FIR Filters

The MATLAB Signal Processing Toolbox includes routines that can be used to apply both FIR and IIR filters. While they are not necessary for either the design or application of FIR filters, they do ease the design of both filter types, particularly for filters with complex frequency characteristics or demanding attenuation requirements. Within the MATLAB environment, filter design and application occur in either two or three stages, each stage executed by separate, but related routines. In the three-stage protocol, the user supplies information regarding the filter type and desired attenuation characteristics, but not the filter order. The first-stage routines determine the appropriate order as well as other parameters required by the second-stage routines. The second stage routines generate the filter coefficients, b(n), based the arguments produced by the first-stage routines including the filter order. A two-stage design process would start with this stage, in which case the user would supply the necessary input arguments including the filter order. Alternatively, more recent versions of MATLAB’s Signal Processing Toolbox provide an interactive filter design package called FDATool (for filter design and analysis tool) which performs the same operations described below, but utilizing a user-friendly graphical user interface (GUI). Another Signal Processing Toolbox package, the SPTool (signal processing tool) is useful for analyzing filters and generating spectra of both signals and filters. New MATLAB releases contain detailed information of the use of these two packages.

The final stage is the same for all filters including IIR filters: a routine that takes the filter coefficients generated by the previous stage and applies them to the data. In FIR filters, the final stage could be implemented using convolution as was done in previous examples, or the MATLAB filter routine described earlier, or alternatively the MATLAB Signal Processing Toolbox routine filtfilt can be used for improved phase properties.

One useful Signal Processing Toolbox routine determines the frequency response of a filter given the coefficients. Of course, this can be done using the FFT as shown in Examples 4.2 and 4.3, and this is the approach used by the MATLAB routine. However the MATLAB routine freqz, also includes frequency scaling and plotting, making it quite convenient. The freqz routine

Copyright 2004 by Marcel Dekker, Inc. All Rights Reserved.

plots, or produces, both the magnitude and the phase characteristics of a filter’s frequency response:

[h,w] = freqz (b,a,n,fs);

where again b and a are the filter coefficients and n is the number of points in the desired frequency spectra. Setting n as a power of 2 is recommended to speed computation (the default is 512). The input argument, fs, is optional and specifies the sampling frequency. Both output arguments are also optional: if freqz is called without the output arguments, the magnitude and phase plots are produced. If specified, the output vector h is the n-point complex frequency response of the filter. The magnitude would be equal to abs(h) while the phase would be equal to angle(h). The second output argument, w, is a vector the same length as h containing the frequencies of h and is useful in plotting. If fs is given, w is in Hz and ranges between 0 and fs/2; otherwise w is in rad/sample and ranges between 0 and π.

Two-Stage FIR Filter Design

Two-stage filter design requires that the designer known the filter order, i.e., the number of coefficients in b(n), but otherwise the design procedure is straightforward. The MATLAB Signal Processing Toolbox has two filter design routines based on the rectangular filters described above, i.e., Eqs. (10)–(13). Although implementation of these equations using standard MATLAB code is straightforward (as demonstrated in previous examples), the FIR design routines replace many lines of MATLAB code with a single routine and are seductively appealing. While both routines are based on the same approach, one allows greater flexibility in the specification of the desired frequency curve. The basic rectangular filter is implemented with the routine fir1 as:

b = fir1(n,wn,’ftype’ window);

where n is the filter order, wn the cutoff frequency, ftype the filter type, and window specifies the window function (i.e., Blackman, Hamming, triangular, etc.). The output, b, is a vector containing the filter coefficients. The last two input arguments are optional. The input argument ftype can be either ‘high’ for a highpass filter, or ‘stop’ for a stopband filter. If not specified, a lowpass or bandpass filter is assumed depending on the length of wn. The argument, window, is used as it is in the pwelch routine: the function name includes arguments specifying window length (see Example 4.3 below) or other arguments. The window length should equal n 1. For bandpass and bandstop filters, n must be even and is incremented if not, in which case the window length should be suitably adjusted. Note that MATLAB’s popular default window, the Hamming

Copyright 2004 by Marcel Dekker, Inc. All Rights Reserved.

window, is used if this argument is not specified. The cutoff frequency is either a scalar specifying the lowpass or highpass cutoff frequency, or a two-element vector that specifies the cutoff frequencies of a bandpass or bandstop filter. The cutoff frequency(s) ranges between 0 and 1 normalized to fs/2 (e.g., if, wn = 0.5, then fc = 0.5 * fs/2). Other options are described in the MATLAB Help file on this routine.

A related filter design algorithm, fir2, is used to design rectangular filters when a more general, or arbitrary frequency response curve is desired. The command structure for fir2 is;

b = fir2(n,f,A,window)

where n is the filter order, f is a vector of normalized frequencies in ascending order, and A is the desired gain of the filter at the corresponding frequency in vector f. (In other words, plot(f,A) would show the desired magnitude frequency curve.) Clearly f and A must be the same length, but duplicate frequency points are allowed, corresponding to step changes in the frequency response. Again, frequency ranges between 0 and 1, normalized to fs/2. The argument window is the same as in fir1, and the output, b, is the coefficient function. Again, other optional input arguments are mentioned in the MATLAB Help file on this routine.

Several other more specialized FIR filters are available that have a twostage design protocol. In addition, there is a three-stage FIR filter described in the next section.

Example 4.4 Design a window-based FIR bandpass filter having the frequency characteristics of the filter developed in Example 4.3 and shown in Figure 4.12.

%Example 4.4 and Figure 4.12 Design a window-based bandpass

%filter with cutoff frequencies of 5 and 15 Hz.

%Assume a sampling frequency of 100 Hz.

%Filter order = 128





clear all; close all;



fs =


% Sampling frequency

order = 128;

% Filter order

wn =

[5*fs/2 15*fs/2];

% Specify cutoff





b =


% On line filter design,




Hamming window

[h,freq] = freqz(b,1,512,100);

% Get frequency response


% Plot frequency response

xlabel(’Frequency (Hz)’); ylabel(’H(f)’);

Copyright 2004 by Marcel Dekker, Inc. All Rights Reserved.

FIGURE 4.12 The frequency response of an FIR filter based in the rectangular filter design described in Eq. (10). The cutoff frequencies are 5 and 15 Hz. The frequency response of this filter is identical to that of the filter developed in Example 4.5 and presented in Figure 4.10. However, the development of this filter required only one line of code.

Three-Stage FIR Filter Design

The first stage in the three-stage design protocol is used to determine the filter order and cutoff frequencies to best approximate a desired frequency response curve. Inputs to these routines specify an ideal frequency response, usually as a piecewise approximation and a maximum deviation from this ideal response. The design routine generates an output that includes the number of stages required, cutoff frequencies, and other information required by the second stage. In the three-stage design process, the firstand second-stage routines work together so that the output of the first stage can be directly passed to the input of the second-stage routine. The second-stage routine generates the filter coefficient function based on the input arguments which include the filter order, the cutoff frequencies, the filter type (generally optional), and possibly other arguments. In cases where the filter order and cutoff frequencies are known, the

Copyright 2004 by Marcel Dekker, Inc. All Rights Reserved.

first stage can be bypassed and arguments assigned directly to the second-stage routines. This design process will be illustrated using the routines that implement Parks–McClellan optimal FIR filter.

The first design stage, the determination of filter order and cutoff frequencies uses the MATLAB routine remezord. (First-stage routines end in the letters ord which presumably stands for filter order). The calling structure is

[n, fo, ao, w] = remezord (f,a,dev,Fs);

The input arguments, f, a and dev specify the desired frequency response curve in a somewhat roundabout manner. Fs is the sampling frequency and is optional (the default is 2 Hz so that fs/2 = 1 Hz). Vector f specifies frequency ranges between 0 and fs/2 as a pair of frequencies while a specifies the desired gains within each of these ranges. Accordingly, f has a length of 2n—2, where n is the length of a. The dev vector specifies the maximum allowable deviation, or ripple, within each of these ranges and is the same length as a. For example, assume you desire a bandstop filter that has a passband between 0 and 100 with a ripple of 0.01, a stopband between 300 and 400 Hz with a gain of 0.1, and an upper passband between 500 and 1000 Hz (assuming fs/2 = 1000) with the same ripple as the lower passband. The f, a, and dev vectors would be: f = [100 300 400 500]; a = [1 0 1]; and dev = [.01 .1 .01]. Note that the ideal stopband gain is given as zero by vector a while the actual gain is specified by the allowable deviation given in vector dev. Vector dev requires the deviation or ripple to be specified in linear units not in db. The application of this design routine is shown in Example 4.5 below.

The output arguments include the required filter order, n, the normalized frequency ranges, fo, the frequency amplitudes for those ranges, a0, and a set of weights, w, that tell the second stage how to assess the accuracy of the fit in each of the frequency ranges. These four outputs become the input to the second stage filter design routine remez. The calling structure to the routine is:

b = remez (n, f, a, w,’ftype’);

where the first four arguments are supplied by remezord although the input argument w is optional. The fifth argument, also optional, specifies either a hilbert linear-phase filter (most common, and the default) or a differentiator which weights the lower frequencies more heavily so they will be the most accurately constructed. The output is the FIR coefficients, b.

If the desired filter order is known, it is possible to bypass remezord and input the arguments n, f, and a directly. The input argument, n, is simply the filter order. Input vectors f and a specify the desired frequency response curve in a somewhat different manner than described above. The frequency vector still contains monotonically increasing frequencies normalized to fs/2; i.e., ranging

Copyright 2004 by Marcel Dekker, Inc. All Rights Reserved.

% Specify ripple
% tolerance in passband % Specify error
% tolerance in passband % Sample frequency: 2
% kHz
% Define frequency % ranges
% Specify gain in % those regions

between 0 and 1 where 1 corresponds to fs/2. The a vector represents desired filter gain at each end of a frequency pair, and the gain between pairs is an unspecified transition region. To take the example above: a bandstop filter that has a passband (gain = 1) between 0 and 100, a stopband between 300 and 400 Hz with a gain of 0.1, and an upper passband between 500 and 700 Hz; assuming fs/2 = 1 kHz, the f and a vector would be: f = [0 .1 .3 .4 .5 .7]; a = [1 1 .1 .1 1 1]. Note that the desired frequency curve is unspecified between 0.1 and 0.3 and also between 0.4 and 0.5.

As another example, assume you wanted a filter that would differentiate a signal up to 0.2fs/2 Hz, then lowpass filter the signal above 0.3fs/2 Hz. The f and a vector would be: f = [0 .1 .3 1]; a = [0 1 0 0].

Another filter that uses the same input structure as remezord is the least square linear-phase filter design routine firls. The use of this filter in for calculation the derivative is found in the Problems.

The following example shows the design of a bandstop filter using the Parks–McClellan filter in a three-stage process. This example is followed by the design of a differentiator Parks–McClellan filter, but a two-stage design protocol is used.

Example 4.5 Design a bandstop filter having the following characteristics: a passband gain of 1 (0 db) between 0 and 100, a stopband gain of −40 db between 300 and 400 Hz, and an upper passband gain of 1 between 500 and 1000 Hz. Maximum ripple for the passband should be ±1.5 db. Assume fs = 2 kHz. Use the three-stage design process. In this example, specifying the dev argument is a little more complicated because the requested deviations are given in db while remezord expects linear values.

%Example 4.5 and Figure 4.13

%Bandstop filter with a passband gain of 1 between 0 and 100,

%a stopband gain of -40 db between 300 and 400 Hz,

%and an upper passband gain of 1 between 500 and fs/2 Hz (1000


%Maximum ripple for the passband should be ±1.5 db


rp_pass = 3;

rp_stop = 40;

fs = 2000;

f = [100 300 400 500];

a= [1 0 1];


Copyright 2004 by Marcel Dekker, Inc. All Rights Reserved.