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

Lab 6 DSP

This document outlines a laboratory exercise focused on designing Finite Impulse Response (FIR) filters using MATLAB. It covers the basics of FIR filters, their types, design methods, and provides MATLAB code examples for implementing various filter types. The lab tasks include analyzing window functions and designing different FIR filters using specified windows.

Uploaded by

Ali Haider
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Lab 6 DSP

This document outlines a laboratory exercise focused on designing Finite Impulse Response (FIR) filters using MATLAB. It covers the basics of FIR filters, their types, design methods, and provides MATLAB code examples for implementing various filter types. The lab tasks include analyzing window functions and designing different FIR filters using specified windows.

Uploaded by

Ali Haider
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Lab # 6

Finite Impulse Response (FIR) Filters I


Objective
The aim of this laboratory is to learn the basis of a digital Finite Impulse Response (FIR) filter
design accordingly to a given filter specification.

Getting help in MATLAB


There are several sources from which help can be obtained. Three of the most commonly used are
represented below. It is strongly recommended that you explore these thoroughly before
proceeding with the other exercises, since they will be useful for all remaining laboratory exercises
for DSP.

MATLAB help window – type “helpwin” at the command prompt. This will launch a new window
where all MATLAB core functions are categorized. To find a function, select the appropriate
category and select the operator you need to learn more about its syntax and operation.

MATLAB help desk – to launch, type “helpdesk” at the command prompt. The help desk will give
you web pages with more detailed help documents and examples of how functions can be used.

MATLAB function help - by typing in “help <function_name>” you can receive help on a
particular function. This is useful if you know the name of the function but are not sure about the
syntax.

MATLAB demos – type in “demo” at the command prompt. This takes you to a window where
simple demos show different capabilities of the software. This is a good starting point for new
users. Throughout out this lab, use the MATLAB beginner’s manual and the MATLAB help pages
as reference.

Filters
Filters are a basic component of all signal processing and telecommunication system. A filter is a
device or process that removes some unwanted components or features from a signal. Filtering is
a class of signal processing used to complete or partial suppression of some aspects of the signal.
Most often, this means to remove some frequencies and not others in order to suppress the
interfacing signals and reduce the background noise.
There are four main types of frequency selective filters: low-pass, high-pass, band-pass and band-
stop as shown in figure below.

Low-Pass Filters: An ideal Low-Pass filter is the one that allows to pass all frequency components
of a signal below a designated cutoff frequency ωc, and rejects to pass all frequency components
of a signal above ωc. Its frequency response satisfies:
High-Pass Filters: An ideal High-Pass filter is the one that allows to pass all frequency
components of a signal above a designated cutoff frequency ωc, and rejects to pass all frequency
components of a signal below ωc. Its frequency response satisfies:

Band-Pass Filters: An ideal Band-Pass filter is the one that allows to pass all frequency
components of a signal within a certain range, and rejects to pass all frequency components of a
signal outside of that range. Its frequency response satisfies:

Band-Stop Filters: An ideal Band-Stop filter is the one that rejects to pass all frequency
components of a signal within a certain range, and allows to pass all frequency components of a
signal outside of that range. Its frequency response satisfies:

Finite Impulse Response Filter


FIR filters are the type of digital filters having a finite impulse response, i.e. the response of the
filter (system) decays after some finite time interval. This means that the impulse response
sequence of FIR filters has a finite number of non-zero terms. In other words, if the impulse
response of a digital filter is determined for some finite number of sample points, then these filters
are known as FIR filters.
The general difference equation for a FIR filter is:

Where "y(n)" is the filter output at discrete time instances "n", "bk" is the k-th feedforward tap, or
the filter coefficient, and "x(n – k)" is the filter input delayed by "k" samples. The "Σ" denotes
summation from k = 0 to k = M -1, where "M" is the number of the feedforward taps in the FIR
filter. Note that the FIR filter output depends only on the previous "M" inputs. This feature is why
the impulse response for a FIR filter is finite.

Infinite response is truncated to get finite impulse response. Placing a window of finite length does
this. Types of windows available are Rectangular, Bartlett, Hamming, Hanning, Blackmann
window etc. This FIR filter is an all zero filter.

a. Inherently BIBO (bounded-input, bounded-output) stable


b. Nonzero pole does not exist in its transfer function
c. Easy to implement
d. Can be designed to have linear phase property (the phase response is a linear function of
frequency.)

Order of an FIR filter is considerably higher than that of an equivalent IIR filter meeting the same
specifications; this leads to higher computational complexity for FIR.
Code A

% Define FIR filter coefficients (impulse response)


h = [0.2, 0.3, 0.5]; % Example coefficients

% Define input signal


x = [1, 2, 3, 4, 5]; % Example input

% Compute output using convolution


y = conv(x, h);

% Display results
disp('Output y[n]:');
disp(y);

Code B

% Define FIR filter coefficients (impulse response)


h = [0.1, 0.15, 0.5, 0.15, 0.1]; % Example coefficients

% Define input signal


x = [3, 1, 0, -1, -3, -1, 0, 1, 3]; % Example input signal

% Apply FIR filter using the filter function


y = filter(h, 1, x); % '1' represents no feedback for FIR filters

% Display input and output signals


disp('Input signal x[n]:');
disp(x);

disp('Filter coefficients h[n]:');


disp(h);

disp('Output y[n] (filtered signal):');


disp(y);

% Plot input and output


figure;
subplot(2, 1, 1);
stem(x, 'filled');
title('Input Signal x[n]');
xlabel('n');
ylabel('Amplitude');
subplot(2, 1, 2);
stem(y, 'filled');
title('Output Signal y[n]');
xlabel('n');
ylabel('Amplitude');

% Define FIR filter coefficients


h = [0.2, 0.3, 0.5]; % Example coefficients

% Create z-domain transfer function


b = h; % FIR filter only has numerator coefficients
a = 1; % Denominator is 1 for FIR filters
H_z = tf(b, a, -1); % Transfer function

% Display transfer function


disp('Transfer Function H(z):');
disp(H_z);

% Plot pole-zero diagram (all zeros, no poles except at origin)


zplane(b, a);
title('Pole-Zero Plot of FIR Filter');

Design a Lowpass FIR Filter:

fs = 1000; % Sampling frequency


fc = 100; % Cutoff frequency
n = 50; % Filter order
b = fir1(n, fc/(fs/2)); % FIR filter coefficients
freqz(b, 1, 1024, fs); % Frequency response
B = fir1(N,Wn) designs an N'th order lowpass FIR digital filter and returns the filter coefficients in length
N+1 vector B. The cut-off frequency Wn must be between 0 < Wn < 1.0, with 1.0 corresponding to half
the sample rate. The filter B is real and has linear phase. The normalized gain of the filter at Wn is -6
dB.
N = 3 ; % Filter order
fc = 120; % Cutoff frequency in Hz
fs = 500; % Sampling frequency in Hz
Wn = fc / (0.5 * fs); % Normalized cutoff frequency
b = fir1(N, Wn); % FIR filter coefficients filter to signal x
fvtool(b, 1)

freqz(b, 1, 1024, fs); % Frequency response of the filter


impz(b)

Code 2 % FIR Filter Design Using Rectangular Window

% Specifications
fs = 1000; % Sampling frequency (Hz)
fc = 150; % Cutoff frequency (Hz)
N = 21; % Filter order (must be odd for
symmetric impulse response)

% Normalized cutoff frequency


Wn = fc / (0.5 * fs); % Normalized to Nyquist frequency
(0.5*fs)

% Rectangular window (default window for fir1)


window_rect = rectwin(N + 1); % Create rectangular
window

% FIR filter design


b = fir1(N, Wn, 'low', window_rect);

% Frequency response of the filter


freqz(b, 1, 1024, fs); % Plot the frequency response
title('Frequency Response of Low-pass FIR Filter Using
Rectangular Window');

% Impulse response
figure;
impz(b);
title('Impulse Response of FIR Filter');

FIR Filter Design using MATLAB


Two MATLAB toolboxes support design of the digital FIR filters: Signal Processing Toolbox (The
MathWorks, Inc. 2010b) and DSP system Toolbox (The MathWorks, Inc. 2010a). The classical
method of windowed linear-phase FIR digital filter design is implemented in function fir1, found
in Signal Processing Toolbox (The MathWorks, Inc. 2010b). Function returns the b coefficients
(see eq. (2.1) and (2.2)) for the Hamming windows based FIR filter of an order n with normalized
cutoff frequency Wn:

N = 21;
fc = 120; % cutoff frequencies equal to 120 Hz
fs = 500; % sampling frequency equal to 500 Hz
Wn = f/(0.5*fs); Simplifies Design Calculations
b = fir1(N, Wn);

The type of the window can be set by adding the additional parameter (window, specified by a
column vector (window_vect) to fir1 function:

N = 51;
window_vect = window(@gausswin,N,2.5); % 2.5 is the spread
b = fir1(N, Wn, window_vect);

The function window can be found in Signal Processing Toolbox (The MathWorks, Inc. 2010b)
and is used to specify various windows (@bartlett, @hann, @barthannwin, @blackman,
@bohmanwin, @chebwin, @kaiser, @flattopwin, @taylorwin, @gausswin, @nuttallwin,
@hamming, @parzenwin, @rectwin, @tukeywin, @triang, @blackmanharris) by a column
vector.

By default, the fir1 function designs the low-pass filter if Wn variable has one value or band-pass
filter if Wn variable is a row vector with two values (Wn = [Wn_low Wn_up]), defining the lower
(W_low) an upper (Wn_up) cutoff frequencies. The other types of the digital filter can be set by
additional parameter ’high’ for the high-pass filter and ’stop’ for the band-stop filter:

n = 50;
Wn_low = 0.2;
Wn_up = 0.4;
Wn = [Wn_low Wn_up];
b = fir1(n, Wn, ’stop’);

Three main characteristics of the FIR filter (impulse response, frequency response and phase
response) can be plotted by the use of impz and freqz functions respectively. MATLABTM Signal
Processing Toolbox (The MathWorks, Inc. 2010b) also offers a Filter Visualization Tool (fvtool)
which enables easy and quick view of various filter characteristics. For FIR filters these
characteristics can be easily extracted without these specialized functions.

FIR Filter Design using FDATool: This mandatory part of the laboratory is dedicated to learn
how to use the innovative MATLAB tools for FIR filter design. This session helps in
understanding the graphical user interface (GUI) for digital filter design found in DSP System
Toolbox (The MathWorks, Inc. 2010a).

1. Start the Filter Design and Analysis Tool


2. Select the filter response type accordingly to the task requirements.
3. Select the appropriate FIR filter design method (Window).
4. Select the type of the window for the truncation of desired filter impulse response.
5. Set the appropriate sampling (Fs) and cutoff (Fc) frequencies.
6. Change the order of the FIR filter to satisfy the given stopband attenuation. If Kaiser
window is used for FIR filter design, the minimum order of the filter should be evaluated
automatically.
FIR Filter Design without GUI (Scripting): This mandatory part focuses on MATLAB Signal
Processing Toolbox (The MathWorks, Inc. 2010b) functions for FIR filter design using classical
methods, such as windowing (fir1).

1. Create an *.m file and name it (e.g., fir_lab.m).


2. Set the order of the designed FIR filter.
3. Prepare the vector of normalized cutoff frequencies.
4. Create the appropriate window vector.
5. Calculate FIR filter b coefficients using fir1.
6. Draw the impulse response, magnitude response and phase response of the filter using
Filter Visualization Tool.

Limitations of FIR Filters


FIR filters have some drawbacks however. The most important is that they can be computationally
expensive to implement. Another is that they have a long transient response. It is commonly
thought that IIR filters must be used when computational power is at the premium. This is certainly
true is some case. However, in many cases, the use of multistage or multi-rate techniques can yield
FIR implementations that can compete (and even surpass) IIR implementations while retaining the
nice characteristics of FIR filters such as linear phase, stability, and robustness to quantization
effects. However, these efficient multistage or multi-rate designs tend to have very large transient
responses, so depending on the requirements of the filter, IIR design may still be the way to go.
Lab Task

1. Analyze following windows in time and frequency domain. Comment on your findings in terms
of Passband, Stopband parameters. You might use windows visualization tool in MATLAB for
this purpose. (Bartlett, Hamming, Hanning, Blackman or rectwin).

2. Design the following versions of Finite Impulse Response (FIR) Filter using fir1() using
windows of your own choice. (Bartlett, Hamming, Hanning, Blackman or rectwin).

a. Low Pass Filter


b. High Pass Filter
c. Band Pass Filter
d. Band Stop Filter

% Sampling frequency
Fs = 1000; % Hz
% Normalized frequencies (divided by Nyquist frequency, Fs/2)
f_low = 0.2; % Low cutoff (normalized, 0 to 1 range)
f_high = 0.4; % High cutoff (normalized, 0 to 1 range)
filter_order = 4; % Order of the filter (can be adjusted)

% Window selection (Choose one: 'bartlett', 'hamming', 'hann', 'blackman', 'rectwin')


window_type = hamming(filter_order + 1); % Change the function for different windows

%% a. Low Pass Filter


% Design filter using fir1
low_pass = fir1(filter_order, f_low, 'low', window_type);
% Frequency response
fvtool(low_pass, 1);
title('Low Pass Filter (FIR)');

%% b. High Pass Filter


% Design filter using fir1
high_pass = fir1(filter_order, f_low, 'high', window_type);
% Frequency response
fvtool(high_pass, 1);
title('High Pass Filter (FIR)');

%% c. Band Pass Filter


% Design filter using fir1
band_pass = fir1(filter_order, [f_low f_high], 'bandpass', window_type);
% Frequency response
fvtool(band_pass, 1);
title('Band Pass Filter (FIR)');

%% d. Band Stop Filter


% Design filter using fir1
band_stop = fir1(filter_order, [f_low f_high], 'stop', window_type);
% Frequency response
fvtool(band_stop, 1);
title('Band Stop Filter (FIR)');

……………………………………
% Filter Specifications
Low Pass FIR Filter
f_p = 1000; % Passband frequency (Hz)
f_s = 1500; % Stopband frequency (Hz)
f_samp = 8000; % Sampling frequency (Hz)
N = 50; % Filter order

% Design FIR filter using Hamming window


h = fir1(N, f_p / (f_samp / 2), 'low', hamming(N+1));

% Transfer Function
b = h; % Numerator coefficients (FIR filter coefficients)
a = 1; % Denominator coefficient for FIR filters (a single 1)

% Display transfer function coefficients


disp('Numerator Coefficients (b):');
disp(b);
disp('Denominator Coefficient (a):');
disp(a);

% Plot Impulse Response


figure;
stem(0:N, h, 'filled'); % Impulse response
title('Impulse Response of FIR Low Pass Filter');
xlabel('Samples (n)');
ylabel('Amplitude');
grid on;

% Plot Frequency Response


figure;
freqz(b, a, 1024, f_samp); % Frequency response
title('Frequency Response of FIR Low Pass Filter');

% Plot Z-plane (Pole-Zero Plot)


figure;
zplane(b, a); % Pole-zero plot
title('Pole-Zero Plot of FIR Filter');
grid on;

Generate a signal in matlab with ten sinusoiudal frequencies and apply low pass filter on it in
matlab.
% Parameters
fs = 1000; % Sampling frequency (Hz)
t = 0:1/fs:1-1/fs; % Time vector (1 second duration)
frequencies = [10, 20, 50, 100, 150, 200, 300, 400, 500, 600]; % 10 frequencies
amplitudes = [1, 0.8, 1.2, 1, 0.7, 0.5, 0.3, 0.2, 0.1, 0.05]; % Amplitudes for each frequency

% Generate Signal: Mixture of 10 sinusoidal frequencies


signal = zeros(size(t));
for k = 1:length(frequencies)
signal = signal + amplitudes(k) * sin(2 * pi * frequencies(k) * t);
end

% Plot the original signal in the time domain


figure;
plot(t, signal);
title('Original Signal (Time Domain)');
xlabel('Time (s)');
ylabel('Amplitude');
grid on;

% Plot the original signal in the frequency domain


N = length(signal); % Number of points for FFT
f = fs*(0:(N/2))/N; % Frequency vector
signal_fft = abs(fft(signal)/N); % Compute FFT
figure;
plot(f, 2*signal_fft(1:N/2+1)); % Plot single-sided spectrum
title('Original Signal (Frequency Domain)');
xlabel('Frequency (Hz)');
ylabel('Amplitude');
grid on;

% FIR Low-Pass Filter Design


fc = 150; % Cutoff frequency (Hz)
filter_order = 50; % Filter order
h = fir1(filter_order, fc/(fs/2), 'low', hamming(filter_order+1)); % FIR filter

% Apply FIR filter to the signal


filtered_signal = filter(h, 1, signal);

% Plot the filtered signal in the time domain


figure;
plot(t, filtered_signal);
title('Filtered Signal (Time Domain)');
xlabel('Time (s)');
ylabel('Amplitude');
grid on;

% Plot the filtered signal in the frequency domain


filtered_fft = abs(fft(filtered_signal)/N); % Compute FFT of filtered signal
figure;
plot(f, 2*filtered_fft(1:N/2+1)); % Plot single-sided spectrum
title('Filtered Signal (Frequency Domain)');
xlabel('Frequency (Hz)');
ylabel('Amplitude');
grid on;

3. Design the following Finite Impulse Response (FIR) Filters using fdatool.

a. Low Pass Filter


b. High Pass Filter
c. Band Pass Filter
d. Band Stop Filter

4. Use Digital Filte to remove noise from a noisy sine signal of 5 Hz. Use FIR with windows design
method.

5. Design a Low-pass filter according to specification below.


• ωp = 0.2π
• ωs = 0.3π
• δ1 = 0.01
• δ2 = 0.01

Below is the complete MATLAB code for the low-pass filter design using the specifications and approach
described:
% Filter specifications
wp = 0.2 * pi; % Passband cutoff frequency (radians)
ws = 0.3 * pi; % Stopband cutoff frequency (radians)
delta1 = 0.01; % Maximum passband ripple
%Passband ripple refers to the variation in the magnitude of the frequency response within the
passband of a filter. 0.010 (1%)
delta2 = 0.01; % Maximum stopband attenuation

% Determine filter order using the Chebyshev approximation formula


delta_min = min(delta1, delta2); % Minimum delta for stricter criteria
delta_max = max(delta1, delta2); % Maximum delta for relaxed criteria
delta = delta_min + delta_max; % Combined delta
A = -20 * log10(delta_min); % A is Minimum stopband attenuation in dB
N = ceil((A - 8) / (2.285 * abs(ws - wp))); % Filter order Formula

% Design the low-pass filter using the fir1 function with Kaiser window
filter_coeffs = fir1(N, wp/pi, 'low', kaiser(N+1, A));

% Plot the frequency response


freqz(filter_coeffs, 1);
title('Frequency Response of the Designed Low-Pass Filter');
% Display filter order and coefficients
disp(['Filter order (N): ', num2str(N)]);
disp('Filter coefficients:');
disp(filter_coeffs);

Questions

1. What are the advantages of using FIR Filters?


2. What is the difference between band-pass and band-stop filters?
3. There are various windows with different shape used for FIR filter design, why do not we use
the simple rectangular window?
4. List three disadvantages of FIR Filters?
5. What is the purpose of the window functions, used for FIR filter design?

You might also like