mat lab report
Format for Lab report for Lab Project 3
Al your report must be typed except for calculations which must be written neatly. Your report is to include the following sections:
1. A cover page
2. Introduction
3. Calculations and Results
4. Conclusion
Cover page:
The report starts with a (typed) cover page indicating
• The title and number of the lab project (highlighted: in bold fonts and larger fonts)
• You name
• Contact information (email)
• Date
• Course number and name
Introduction:
This section starts on a new page after the cover page. It summarizes your lab project and the background and motivation for it.
Calculations and Results:
This section includes all your calculations and Matlab printouts. Answer all questions asked in the lab handout. Show all your calculations. Your calculations must be written neatly. Printouts of all m-files you were asked to write and any Matlab calculations and all plots must be included and properly labeled.
Conclusion:
Summarize your results. State if and how your objectives were achieved and if not why, if and how you liked this lab project, and any comments and suggestions you may have on how it could be improved
Discrete-Time Signals & Systems
Laboratory Project 3:
Design of Digital Filters
I- Objectives:
In this lab project you will learn to use Matlab to
· design FIR filters in the discrete-time domain
· design FIR filters to perform:
· image edge detection
· image blurring
· find the frequency response of a FIR filter:
· plot its magnitude and phase vs. normalized frequency
· draw the pole-zero plot
· design a lowpass filter using an L-point running sum filter
· design a bandpass filter using an L-point running sum filter
· design a high-pass filter from the first difference filter
· design a nulling filter to block unwanted tones
· Design FIR filters using the window method
· Design IIR filters:
· find and plot the frequency response
· find the poles and zeros of the system function and draw the pole-zero plot
· observe how the frequency response changes as the locations of poles and zeros change.
II- Introduction:
In this lab project you will learn to use some Matlab functions to design Finite Impulse Response (FIR) and Infinite Impulse Response (IIR) filters. The DSP toolbox of Matlab also provides interactive GUI’s that allow for quick and efficient design of filters. There are open source equivalents of Matlab such as Scilab (which you can download for free at http://www.scilab.org/).
Given the filter coefficients, you will design the following FIR filters: a running average FIR filter of arbitrary length, a FIR filter to detect edges in an image, and a FIR filter to blur an image. You will also learn to use the Matlab function freqz to find and plot the magnitude and phase of the frequency response of a FIR filter. You will observe what happens as the filter coefficients are changed. You will design lowpass and bandpass FIR filters. Next, you will design a FIR filter using the window method. You will then design a nulling filter that blocks undesired tones in an audio recording. You will then design an IIR filter given its coefficients or system function H(z). You will learn how to find the frequency response and the pole-zero plots and how to shape the frequency response by manipulating the location of the poles and zeros of the system function. Poles placed near the unit circle will tend to increase the magnitude of the frequency response or system function H(z) near them. Zeros on the unit circle are frequencies at which the magnitude of H(z) = 0. A zero near the unit circle will tend to reduce the magnitude of the frequency response or system function near them. In order for an IIR filter to be realizable, it has to be causal and stable (i.e. its output always bounded). Stability requires that all the poles of the system function H(z) lie inside the unit circle. FIR filters are always stable and this is one of their advantages. FIR filters are however generally more computationally intensive. IIR filters are most common as analog filters. You will also verify that they offer more flexibility in shaping the frequency response. However, It must always be ensured that their poles lie inside the unit circle in order for them to be stable.
In this lab project, you will be writing several script files that you can reuse in future applications with minimal changes (such as by inputing different filter coefficients or filter orders). It is therefore recommended that you save these files. All screenshots of your results must be saved on your computer and included in your lab report. If you use a college computer, make sure you save these files on a flash disk. The lab report must be written following the guidelines posted in the lab folder on Blackboard.
References:
The related topics from the textbook (DSP First a Multimedia Approach, 1st Ed.) and lectures involve Chapters 5, 6,7, and 8.
III- Procedure and Analysis:
Part 1: Design using FIR Filters in the time domain
Create a new Matlab script file named lab3_part1. For this click on Editor, New, Script. Enter the following Matlab commands in the script file.
% Filters discrete-time input signals in the time domain using
% the Matlab convolution operation
nn=0:99; % n time interval
M=30; % Filter order
xx = cos(0.08*pi*nn); % input signal
bb = 1/M*ones(1,M);% Running average filter coefficients
yy = conv(bb,xx); % Matlab function for convolution
subplot(2,1,1);
stem(nn, xx)
subplot(2,1,2);
mm=0:99+M-1;
stem(mm, yy,'filled');
xlabel('time index n')
Save the file (Click on editor, save as). Run it (click on Run). Print a screenshot of the script file and the resulting plots.
What is the amplitude of the output yy[n] near the edges and in the middle? Is this as expected? By the definition of convolution operation the length is expected to be M + N - 2. What is the length of the output from the plot? Now in the command window of Matlab (bottom) type
>> yy then enter.
This will display the values of the convolution (the output). What is the index of the last value? Does this satisfy the above formula? Confirm by typing
>> length(yy) then enter
Repeat the above by changing the order of the filter to M = 10. What do you notice for the output yy[n] (the convolution of h[n] with the input)? Is this as expected? What do you conclude as the filter order M increases?
Now repeat the above steps for a input pulse defined as xx[n] = 1 for n = 0 to 99. It can be written as xx = ones(1,100). Make a copy of the above script file and save it as a new file called Lab3_Part1_2. Then make the necessary changes so that the new script file will look as follows:
M=30; % Filter order
xx = ones(1,100) % Pulse input signal
bb = 1/M*ones(1,M);% Running average filter coefficients
yy = conv(bb,xx); % Matlab function for convolution
subplot(2,1,1);
stem(nn, xx)
subplot(2,1,2);
mm=0:99+M-1;
stem(mm, yy,'filled');
xlabel('time index n')
Part 2: FIR filter applications in image processing (optional: extra credit):
1. Blurring an image ((optional: extra credit):
In this section, you will use a running average FIR filter to blur an image. This uses the lowpass property of this filter to smooth out edges. The image file is called image.jpg. Download the image file from Blackboard (go the the labs folder) to your desktop. Then upload it to Matlab as follows: Click on home on the top toolbar then on upload, the image file from your desktop. This file should now be listed in the directory “current folder” the left window.
The conv2 function (conv2(image, bdiffh)) is Matlab’s two-dimensional convolution that performs convolution on every row of the array representing the image. A similar convolution operation (conv2(image,bdiffh’))does convolution on all columns of the image.
One-dimensional FIR filters, such as running averagers and first-difference filters, can be applied to one-dimensional signals such as speech or music. These same filters can be applied to images if we regard each row (or column) of the image as a one-dimensional signal. For example, the 50th row of an image is the N -point sequence xx[50,n] for 1 to N , so we can filter this sequence with a 1-D filter using the conv operator. Conv2 is more efficient as it performs convolution all all rows or columns.
One objective of this lab is to show how simple 2-D filtering can be accomplished with 1-D row and column filters. In the script file below, you will
(a) after uploading the image on Matlab as you did above, this will create the variable image array whose size is 257 by 256. We can filter all the rows of the image at once with the conv2( ) function. To filter the image in the horizontal direction using a first-difference filter, we form a row vector of filter coefficients and use the following MATLAB statements: bdiffh = [1, -1];
yy1 = conv2(image, bdiffh);
The filter coefficients bdiffh for the first-difference filter are stored in a row vector and will cause conv2( ) to filter all rows in the horizontal direction.You will display the input image and the output image yy1 on the screen at the same time by using imshow().
. (b) You will then filter the image input image in the vertical direction with a first-difference filter to produce the image yy2. This is done by calling yy2 = conv2(image,bdiffh’) with a column vector of filter coefficients.
Now create a script file named Lab3_part2_blurring
Enter the following Matlab commands:
% Blurs an input image by using the Matlab 2D
% convolution function that acts on all rows or on all columns of the
% image array. Displays original and filtered images
subplot(3,2,1);
I = imread(‘image.jpg'); % This reads the input image image.jpg as 3D array
I = I(:,:,1); % This reduces the image array dimension
imshow(I); % This displays the reduced input image
subplot(3,2,2)
M = 1; % M + M + 1 point running average filter
bdiffh = 1/M*ones(1,M); % Filter coefficient: M+1 point running average
yy1 = conv2(I,bdiffh); % 2D convolution on all rows of image array
imshow(yy1); % Displays the row-filtered image
subplot(3,2,3)
yy2 =conv2(I,bdiffh' ); % 2D convolution on all columns of image array
imshow(yy2); % Displays the column-filtered image
Save and Run the script file. Get a screenshot of the script file and your plots.
In the above script file, what is the order M of the running average filter?
Repeat the above steps by changing the order of the filter to 5, and then to 10.
How do the results compare? Is that expected? Why?
2. Detecting edges in an image :
A very simple FIR filter to detect edges in an image is the first difference FIR filter with coefficients bb = [1 -1]. As the filter window slides, convolution acts on each row from left to right, the output y[n] = x[n] - x[n - 1] is zero until it meets an edge (boundary between white and the black of the letters) after the edge it is again zero until the next edge.
First Download to your desktop the following images that you will find in the lab folder on Blackboard:
ImageDec03.jpg’,
image.jpg,
tennis-ball.jpg
tennis-ball2.png
tennis-ball3.jpg
tennis-ball4.jpg
tennis-ball5.png
blackwhitephoto.jpg
Then upload the above image files to Matlab by clicking on Home, Upload, filename from your desktop. All these files should appear now in the list on the left window “Current Folder”
Create a new script file named Lab3_part2_edge_detection
Enter the following commands in the script file:
% Detects the edges of an image by using the Matlab 2D
% convolution function that acts on all rows or on all columns of the
% image array
subplot(3,2,1);
I = imread('ImageDec03.jpg');
I = I(:,:,1); % This reduce the image dimension
imshow(I); % Display origina limage imageDec03
subplot(3,2,2)
bdiffh = [1 -1]; % Fist difference order FIR filter coefficents
yy1 = conv2(I,bdiffh); % Matlab 2D concvolution function that acts on all rows
imshow(yy1) % Display the row-filtered image
subplot(3,2,3)
yy2 = conv2(I,bdiffh'); % Matlab 2D convolution that acts on all columns
imshow(yy2) % Display the column-filtered image
Note that conv2 is used twice, to perform convolution on all rows and all columns of the image array (image Dec03) respectively and display the results.
Repeat the above steps for each of the other images by replacing in the above script file the command:
I = imread(‘ImageDec03.jpg');
successively with:
I = imread(‘image.jpg’);
I = imread(‘tennis-ball.jpg’);
I = imread('tennis-ball2.png');
I = imread('tennis-ball3.jpg');
I = imread('tennis-ball4.jpg');
I = imread('tennis-ball5.png');
I = imread(‘blackwhitephoto.jpg');
Obtain screenshots for each image simulations as you did above.
Part 3: Design of FIR filters in the frequency domain
Matlab has the following function to calculate the frequency response of a FIR filter and plot its magnitude and phase vs. normalized frequency:
Freqz(bb, aa) where bb = [b0, b1 …] is the array of filter coefficients and aa is 1 for FIR filters.
Design of a low pass filter by using an L-points running average filter:
Both in the lecture and textbook, a L-point running sum lowpass filter and a bandpass filter were discussed. In this section ,you will design this filter with Matlab and study how the order affects the frequency response and the pole-zero plots. Matlab uses the zplane () function to compute and plot the pole-zero plots. The real (x) and imaginary (y) parts can be obtained by hovering the cursor with the mouse over their symbols (x: poles, o: zeros).
Create a new script file called Lab3_Part3_1
Write the following Matlab commands:
% Design of a lowpass filer using an L-point running sum
M = 10; %--Filter order
bb = ones(1,M); %--Filter coefficients
ww = -pi:(pi/500):pi; %-- omega hat frequency vector
H = freqz(bb, 1, ww); %<--Matlab function for frequency response
subplot(2,1,1);
plot(ww, abs(H)), grid on
subplot(2,1,2);
plot(ww, angle(H)), grid on
xlabel('Normalized Radian Frequency')
zplane(bb,1); % pole-zero plots
Save (click on edit then save as) and run the script file and get a screenshot of the script file and plots. This should give the results of the 11-point running average filer discussed in class and in your textbook. Are the results as discussed?
Now practice with increasing the filter order M by repeat the above steps and changing the order to M = 15, 20, and 30. What happens on the pole-zero plot and the frequency response. Make sure you get a screenshot of all the results (script file and plots). Write the real and imaginary parts of all the zeros and poles. Do the zeros lie on the unit circle as discussed in class?
Design of a bandpass filter using an 11-points running average filter:
In class and the textbook (chapt. 7) it was shown that a bandpass filter can be designed from an L-point running sum filter.
Create a new script file called Lab3_Part3_2
Write the following Matlab commands:
% Bandpass filter obtained form 11 points running average filter
M = 10; %--Filter order
%bb = [1 -1]; %-- Filter Coefficients
kk = [1 2 3 4 5 6 7 8 9 10]; % for a general M order write a similar array up to M
w0 = pi/3; %—Center of the bandpass
bb = cos(w0*kk); % New filter coefficients that rotate the zeros by w0
ww = -pi:(pi/500):pi; %-- omega hat frequency vector
H = freqz(bb, 1, ww); %<--Matlab function for frequency response
subplot(3,1,1);
plot(ww, abs(H)), grid on
subplot(3,1,2);
plot(ww, angle(H)), grid on
xlabel('Normalized Radian Frequency')
subplot(3,1,3);
zplane(bb,1); % pole-zero plots
Save (click on edit then save as) and run the script file and get a screenshot of the script file and plots. Record the real and imaginary parts of the zeros and poles. Are the zeros on the unit circle? Where is the band pass now centered (check this both in the frequency response plot and the pole-zero plot)?
Now in the above script file, change the center frequency of the bandpass to w0 = 2*pi/3 and repeat the above steps. How does the new plots compare to the previous one? Are the plots as expected?
Design of a high-pass filter from a First Difference Filter:
Here you will design a simple high pass filter by using the first difference filter.
Repeat by changing the filter coefficients to that of a first difference filter (filter coefficients bb = [1 -1].
Create a new script file called Lab3_Part3_3
bb = [1 -1]; %-- Filter Coefficients
ww = -pi:(pi/500):pi; %-- omega hat frequency vector
H = freqz(bb, 1, ww); %<--Matlab function for frequency response
subplot(2,1,1);
plot(ww, abs(H)), grid on
subplot(2,1,2);
plot(ww, angle(H)), grid on
xlabel('Normalized Radian Frequency')
zplane(bb,1); % pole-zero plot
How many zeros are there? Which frequency is blocked? What type of filter is this (lowpass, bandpass, high pass…)? Read and record the real and imaginary parts of the zeros and poles.
Part 4: Design of FIR filters using the windowing method:
The concept of windowing is widely used in signal processing. The basic idea is to extract a finite section of a very long signal x[n] via multiplication w[n].x[n]. This approach works if the window function w[n] is zero outside of an interval. For example, consider the simplest window function which is the L-point rectangular window defined as
w[n] =1 for 0< n < L-1
w[n] 0 elsewhere
The impulse response for an ideal lowpass filter can be shown to be the sinc function
is the cutoff frequency of the ideal LPF, which separates the passband
from the stop band ( defined in Fig. 1 below).
One simple approach to designing a practical FIR filter is to truncate the impulse response of an ideal filter (which is infinite in length). This can be accomplished with a window function, so we usually say that the practical FIR filter has an impulse response that is a windowed version of the ideal impulse response. For example, we could make a length-23 FIR lowpass filter by taking the center portion of the sinc function:
where wr[n] is a 23-point rectangular window.
Procedure:
Create a new script file called Lab3_part4
Write the following commands:
% Filter design with the Window method
M = 22; %-- even Filter order
nn = 0:M; %--'n' index vector
nsh = nn - M/2; %--- Put main lobe in center of h[n]
wb = 0.32*pi; %-- 'Bandwidth parameter' of sinc
bb = sin(wb*nsh)./(pi*nsh); %-- Filter Coefficients
bb(find(nsh==0)) = wb/pi; %-- fix the divide by zero
ww = -pi:(pi/500):pi; %-- omega hat frequency vector
H = freqz(bb, 1, ww); %<--Matlab function for frequency response
subplot(3,2,1);
plot(ww, abs(H)), grid on % Plot magnitude
subplot(3,2,2);
plot(ww, angle(H)), grid on % Plot phase
xlabel('Normalized Radian Frequency')
subplot (3,2,3)
zplane(bb,1); % Pole-zero plot
Save and run the file and get a screenshot of the file and plots. Is this a lowpass, highpass or bandpass filter? Are the results as expected. Read and record the real (x) and imaginary (y) parts values of the zeros and poles by hovering with the mouse over their symbols (x: poles, o: zeros). How close are the zeros to the unit circle where frequencies are strongly attenuated?
Repeat the above by changing the filter order to M = 10, 30, 50, 80.
Each time save and run the file and get a screenshot of the file and the plots.
Is this a low pass, high pass or bandpass filter? How do the plots change and compare? How does this filter compare to the lowpass filter obtained a previous section (based on L-point running sum filter) What do you conclude?
Part 5: Design of a Nulling filter to block undesired tones:
In many applications, we wish to block some undesirable frequencies, such as the parasitic 60 Hz frequency originating from the mains. In the following, you will design a nulling filter that blocks 3 frequencies of tones that were added to a voice recording. You will first upload the recoded voice “SunshineSquare. wav”. To do this you go to Blackboard in the labs folder, and download this file to your desktop. Then go to Matlab click on Home, and upload this file. This file will be added to the list on the left “current folder” window.
As discussed in class and your textbook (Chapt. 7) a nulling filter can be considered a cascade of first order filters whose system function is of the form:
Hk(z) = (1 - 2cos(ωk)z-1 + z-2)
where the kth blocked normalized frequency is ωk . To block dc the following system function is required:
H0(z) = (1 - z-1)
Here 3 tones are to be blocked, in addition to dc. The system function of the cascade is
H(z) = H0(z)*H1(z)*H2(z)*H3(z)
= (1 - z-1)(1 - 2cos(ω1)z-1 + z-2) (1 - 2cos(ω2)z-1 + z-2) (1 - 2cos(ω3)z-1 + z-2)
The following script file will plot the spectrogram of the audio file. From this spectrogram you will be able to identify the undesirable frequencies (correspond to the yellow vertical bands).
To get the filter coefficients bk of the cascade you can multiply out the above factor form of the system function and then take the inverse z- transform. The bk coefficients will be the coefficients of the overall system function H(z). Here you will use the convolution function conv( ) to find the unit impulse response directly in the time n-domain as h = convolution of h0, h1, h2, and h3. The output yy[n] is then computed as the convolution of h[n] and the input xx[n].
This is output as an analog sound where you will hear how this filter has blocked the undesirable frequencies. You will also calculate the frequency response and plot its magnitude and phase vs. You will then output the unfiltered audio file and compare.
Create a new script file named Lab3_tone_removal.m.Write the following commands:
% This will block three tones from an audio recording,
% where the tones were added to a voice recording.
%The frequencies of the tones are identified from the spectrogram
% then a filter developed to block them as well as dc.
% The output is heard and compared to the input. The frequency response is plotted.
[xx, fs] = audioread('SunshineSquare .wav’); % input audio file
xx = xx’; % transforms the row vector into a column vector
subplot (4,1,1)
spectrogram(xx, [ ],fs) % spectrogram and sampling frequency fs. toes to
% be removed are the higher amplitude (yellow vertical stripes) frequencies)
subplot (4,1,2)
bb0 = [1 -1]; % Filter coefficients to block dc
bb1 = [1 -2*cos(0.285*pi) 1]; % Filter coefficients to block the first one
bb2 = [1 -2*cos(0.57*pi) 1]; % Filter coefficents to block the 2nd tone
bb3 = [1 -2*cos(0.86*pi) 1]; % Filter coefficients to block the 3d tone
bb =conv(bb3,conv(bb2,conv(bb1,bb0))); % convolution of the impulse response of
% the cascade of the 4 blocking filters
yy = conv(bb,xx); % filtered output
spectrogram(yy,[],fs) % spectrogram of the output
soundsc(yy,fs) % analog output as sound
subplot (4,1,3)
ww = -pi:pi/500:pi; % Normalized frequency array
H = freqz(bb,1,ww); % frequency response of the nulling filter
plot(ww, abs(H)), grid on % plot magnitude of frequency response
subplot (4,1,4)
plot (ww,angle(H)), grid on % plot phase of frequency response
xlabel('Normalized Radian Frequency')
Save this file then run it (click on editor, save, run).
Listen to the filtered recorded voice.
Now to play the original unfiltered audio file in the Matlab Command window (bottom) enter:
>> soundsc(xx, fs)
How do the filtered and unfiltered audio files compare? Are the undesirable tones noticeably suppressed? Note that if you still hear some of the tones this will be because the actual frequencies read from the spectrogram are approximate and need to be more fine tuned.
Look at the spectrograms of the input and output audio files? are the undesirable tones (yellow vertical stripes) removed?
Now look at the frequency response magnitude plot. At what normalized frequencies is it = 0? Compare these frequencies to the undesirable tine frequencies that you intended to suppress. Are they the same as indicated on the spectrogram of the unfiltered audio signal? What do you conclude?
Take a screenshot of the script file and plots.
Part 6: Design of IIR filters
An IIR Filter of order N is defined by the recursive difference equation:
y[n] = a1 y[n-1] + a2 y[n-2] + ….. + aN y[n-N] + b0x[n] b1x[n-1] +…. + bM x[n-M]
and alternatively by the system function
H(z) = ( b0 + b1 z-1 ….. + bM z-M ) / (1 + a1 z-1 + a2 z-2 …… + aN z-N )
The filter is specified by 2 arrays of coefficients:
aa = [1, a1,…, aN]
bb = [b0, b1,…, bM]
In the z-domain it is defined by its system function H(z). The zeros of H are the values of z for which H(z) = 0. The poles are the values for which H(z) is infinite. The frequency response is given by the Matlab function freqz(bb,aa). The plot of poles and zeros on the complex or z plane, including the unit circle (on which the system function becomes the frequency response) is given by zplane(bb,aa). To get the real part (x) and imaginary part (y) of the poles and zeros, hover with the mouse over their symbols ( x: poles, o: zeros).
IIR filters are most common as analog filters. They provide more versatility than FIR filters in that one can move both the poles and zeros at wish close to the desired region near the unit circle in order to better shape the frequency response. With FIR filters all poles are fixed at the origin.
However, with IIR filters, one has to make always sure the poles are within the unit circle, for otherwise it will be unstable and therefore unrealizable which is not an issue with FIR filters.
Create a script file called Lab3_part6.
Write the following commands:
% Computes the frequency response for an IIR filter given its coefficients.
% Displays magnitudes and phase plots and pole-zero plot of the corresponding
% system function
bb = [64 300 50]; %-- Numerator coefficients of system function H(z)
aa = [1 0.68 0.64] % —Denominator coefficients of system function H(z)
ww = -pi:(pi/500):pi; %-- omega hat radian frequency vector
H = freqz(bb, aa, ww); %— frequency response
subplot(3,1,1);
plot(ww, abs(H)), grid on % Plot magnitude of H
ylabel('Magnitude')
subplot(3,1,2);
plot(ww, angle(H)), grid on % Plot phase of H
ylabel('Phase')
xlabel('Normalized Radian Frequency')
subplot(3,1,3)
zplane(bb,aa)% computes and plots the poles and zeros of system function H(z)
Save and run the file and get a screenshot. What type of filter is this (lowpass, bandpass, highpass, etc.)? In what range of frequencies is the output strongly attenuated? Which frequency ranges are passed (near peaks). Look at the pole-zero plot. Is there a zero or pole near these frequencies. Hover with the cursor of the mouse over the poles and zeros and record their real (x) and imaginary (y) parts. Note that frequencies (normalized) are the angles on the unit circle. Repeat for regions where there is a peak in the frequency response and output.
Now repeat the above steps after changing the IIR filter coefficients in the script file as follows:
bb = [64 180 100];
aa = [1 0.68 4.64];
Repeat again for the following filter coefficients:
bb = [64 300 50];
aa = [1 0.68 0.64];
Practice as above by using different filter coefficients aa and bb. You do not need to submit these
latter results.
IV- Conclusion:
Write a conclusion summarizing your results. Were your objectives met? Where your results as expected? If not why? What are your thoughts about this lab project and suggestions if any to possibly improve it.
Image files to upload to Matlab
4