Department of Electrical Engineering
Faculty Member: ___Kaleem ullah__________ Dated: _16/2/2024_______________
Course/Section: BEE-13A Semester: spring 2024
EE-330 Digital Signal Processing
Lab1: MATLAB REVIEW-Signals & Systems Fundamentals
PLO4-CLO4 PLO5- PLO8- PLO9-
CLO5 CLO6 CLO7
Name Reg. No Viva / Analysis Modern Ethics Individual
Quiz / Lab of data in Tool and and Team
Performa Lab Usage Safety Work
nce Report
5 Marks 5 Marks 5 Marks 5 Marks 5 Marks
Syed Muhammad Tayyab 375498
Danyal Irfan Butt 396404
Ali Hasan Bukhari 371694
Abdul Moiz 370745
Lab1: MATLAB REVIEW-Signals & Systems Fundamentals
Objectives
The purpose of this lab is to review the
fundamentals of signals and systems with MATLAB,
particularly
:
✓ Signal transformations (shifting, inversion, scaling)
✓ Even and Odd parts of a signal
✓ Convolution operator
-the basic property of Linear Time Invariant (LTI) Systems
Lab Instructions
✓ The students should perform and demonstrate each lab task separately for step-wise evaluation
Each group shall submit one lab report on LMS within 5 days after the lab is conducted. Lab
report submitted via email will not be graded.
✓ Students are encouraged to practice on their own in spare time to enhance their skills.
Lab Report Instructions
All questions should be answered precisely to get maximum credit. Lab report must ensure following
items:
✓ Lab objectives
✓ MATLAB codes
✓ Results (graphs/tables) duly commented and discussed.
✓ Conclusion
1.1 Matrices/vectors in MATLAB
(a) Make sure that you understand the colon notation. In particular, explain in words what the following
MATLAB code will produce
jkl = 0 : 6;
Creates an array from 0 to 6 with gap of 1.
jkl = 4 : 4 : 17;
Creates an array from 4 to 17 with gap of 4.
jkl = 99 : -1 : 88;
Creates an array from 99 to 88 with decrement of 1.
ttt = 2 : (1/9) : 4;
Creates an array from 2 to 4 with gap of (1/9).
tpi = pi * [ 0:0.1:2 ];
Creates an array from 0 to 2 with gap of 0.1 and amplitude of pi.
(b) Extracting and/or inserting numbers into a vector is very easy to do. Consider the following definition
of xx:
xx = [zeros(1,3), linspace(0,1,5), ones(1,5)];
[s1 s2] = size(xx); s3
= length(xx);
Explain the results echoed from the last four lines of the above code.
• The first part of first line zeros(1,3) creates a 1 x 3 array of zeroes which means that it gives us [0
0 0]
• The second part of first line linspace(0,1,5) creates a 1 x 5 array of 0.25 difference which means
that it gives us [0 0.25 0.5 0.75 1 ] in front of zeroes function.
• The third part of first line ones(1,5) creates a 1 x 5 array of 1 which means that it gives us [1 1 1 1
1 ] in front of zeroes and linspace function.
• The second line give us size of matrix in form of rows and columns.
• The third line gives us length of matrix i.e highest dimension of matrix.
What’s the difference between a length and a size statement for a matrix? To test this define a matrix X
with arbitrary inputs, having multiple rows and columns and test the output of length() and size() function
on it.
Ans: size() gives us dimension of matrix i.e how many rows and columns it has while length() gives
us the highest dimension of matrix.
xx = [zeros(5,7)] [s1
s2] = size(xx) s3 =
length(xx)
size = 5 7 and length = 7
xx = [zeros(7,5)] [s1
s2] = size(xx) s3 =
length(xx)
size = 7 5 and length = 7
(c) Assigning selective values in a matrix differently. Comment on the result of the following
assignments:
yy = xx;
yy(4:6) = pi*(1:3);
First line assigns xx array to yy and in second line at the index from 4 to 6 pi array with gap of 1 is
created and is changed with the values of the yy function.
1.2 Creating a M-file
Go to File > New > M–file. MATLAB editor will open up. Enter the following code in the editor and
then save the file as Namelab1.m
tt = -1 : 0.01 : 1; xx
= cos( 5*pi*tt );
zz = 1.4*exp(j*pi/2)*exp(j*5*pi*tt);
plot( tt, xx, ’b-’, tt, real(zz), ), grid on
title(’TEST PLOT of a SINUSOID’)
xlabel(’TIME (sec)’)
Now go to Command Window and type
mylab1 %<---will run the commands in the file
type mylab1 %<---will type out the contents of
% mylab1.m to the screen
Result:
1.3 Functions-Key to Efficient Coding
It is often convenient to define functions so that they may used at multiple instances and with different
inputs. Functions are a special type of M-file that can accept inputs (matrices and vectors) and may return
outputs. The keyword function must appear as the first word in the M-file that defines the function, and
the first line of the M-file defines how the function will pass input and output arguments. The file
extension must be lower case “m” as in my func.m. The following function has a few mistakes. Before
looking at the correct one below, try to find these mistakes (there are at least three):
Matlab mfile [xx,tt] = badcos(ff,dur)
%BADCOS Function to generate a cosine wave
% xx = badcos(ff,dur)
% ff = desired frequency in Hz
% dur = duration of the waveform in seconds tt =
0:1/(100*ff):dur; %-- gives 100 samples per period
badcos = cos(2*pi*freeq*tt);
The corrected function should look something like:
function [xx,tt] = goodcos(ff,dur)
tt = 0:1/(100*ff):dur; %-- gives 100 samples per period
xx = cos(2*pi*ff*tt);
Notice the word “function” in the first line. Also, “freeq” has not been defined before being used. Finally,
the function has “xx” as an output and hence “xx” should appear in the left-hand side of at least one
assignment line within the function body. The function name is not used to hold values produced in the
function.
1.4 Review of Basic Signals and Systems
a) Even and odd parts of a signal:
Any signal x[n] can be decomposed into its even part and odd parts as:
𝑥𝑒(𝑛)= [𝑥(𝑛)+𝑥(−𝑛)]
𝑥0(𝑛)= [𝑥(𝑛)−𝑥(−𝑛)]
Write a simple MATLAB code (in the form of a function) that allows you to decompose a signal into its
even and odd parts.
Note: The function takes two inputs n, the timing index and x the values of the signal at the designated
time instants. The function outputs include the two sub-functions, x_e and x_o along with the timing
index.
Test your function on the following signal x[n] and compute its even and odd parts.
2 𝑛=0
5 𝑛=1
𝑥[𝑛]= −1 𝑛=2
4 𝑛=3
−5 𝑛=4
{0 elsewhere
Code
n=[0 1 2 3 4]; yn= [2 5
-1 4 -5];
yflip=fliplr(yn);
subplot(3,1,1);
stem(n,yn,'r',LineWidth=
2); title('plot of yn');
xlabel('time');
ylabel('yn');
ye = (1/2)*(yn+yflip);
subplot(3,1,2);
stem(n,ye,'b',LineWidth=2);
title('plot of even');
xlabel('time');
ylabel('y even');
yo= (1/2)*(yn-
yflip);
subplot(3,1,3);
stem(n,yo,LineWidth=
2); title('plot of
odd');
xlabel('time');
ylabel('y odd');
Output
b) First order Difference equation:
Recall that one way of defining the LTI systems is through the difference equations that relate the
input x[n] to the output y[n].
Consider the first order system defined by the difference equation as follows (we’ll review the
discussion on how determination of order for a difference equation later):
y[n] = a. y[n-1] + x[n]
Write a function y = diffeqn (a, x, y[-1]) which computes the output y[n] of the system determined by
the given equation. The vectors x[n] contains the signal as defined in the upper part and y[n] = 0 for
n < 1.
Code
Diffeqn.m function [y_n] =
diffeqn(a,x,y_i) y_n =
zeros(1,length(x)); if
length(y_n) >= 1
y_n(1) = a * y_i + x(1); if
length(y_n) > 1 for i =
2:length(y_n) y_n(i) = a *
y_n(i-1) + x(i); end end
else y_n = 0; end
end
Output
Explanation
The first test is to check how many elements x has, if it does not have any we need to return 0
at the output so we do that using an if statement, then next we have to check if it is equal to
one or more then one, if it has more then 1 we will only then we can apply the for loop to get
y if it does not then we only need to return the single output y which we can denote from the
original expression.
c) Convolution of signals
Recall that one the most convenient ways to represent an LTI system is through its impulse response
h[n]. Once the impulse response of a system is known, the output (response) of the system to any
given input can be computed using the convolution operator as:
yn= xkhn−k
k=−
The convolution essentially involves two operations: flipping either the input signal or the impulse
response (as in above equation) and then sliding the flipped signal.
i. Write your own convolution function, myconv.m that computes the convolution between the two signals
(or the output of passing an input signal through a system). Designate all the necessary inputs for your
function, considering that the input signal and the impulse response may start at some ‘n’ that is
negative. The function output is obviously the system output along with the timing index for the output
n1, which must be set manually. Your function should work on any general signal and the impulse
response (of finite length).
Code
Myconv2.m function [final_domain, final_range] =
myconv2(domain_1,x_1,domain_2,h) domain_info= zeros(length(x_1),
length(h)); range_info = zeros(length(x_1), length(h));
for i = 1:length(x_1)
[shifted_domain, range] = shift(domain_2, h, -1*domain_1(i));
domain_info(i,:) = shifted_domain; range_info(i,:) = x_1(i)
* h;
end minimumDomainValue = min(min(domain_info));
maximumDomainValue = max(max(domain_info));
final_domain = minimumDomainValue: maximumDomainValue;
final_range = zeros(1,length(final_domain)); for
j=1:length(final_domain)
[row,col] = find(domain_info == final_domain(j));
for k = 1:length(col)
final_range(j) = final_range(j) + range_info(row(k),col(k));
end
stem(final_domain,final_range) end
shift.m
function [domain,shifted_output] = shift(x,range, shiftBy)
domain = x - shiftBy;
shifted_output = range; end
Explanation
This code uses two dimensional matrix to keep track of the domain shifting we have done at
every point, this is done by the use of for loop and as we know that the number of values that
x contains only that amount of times h will be shifted and then added, this is why we kept the
number of rows of the 2d matrice as the length of the 1d vector x. Inside the first for loop I do
the time shifting in which the signal is shifted by the domain of the x signal and save it in the
first row and then for the second value and then shift it like that.
Next step is the save the range of the signal I do this by doing x(k) * the h array which
changes the amplitude of the h array.
Next step is to make the final 1d signal for which we need to find the minimum value that
exists inside of the domain_info 2d matrix and go up to the maximum value contained inside
the domain matrix with a gap of 1 since it is a discrete time signal.
Now as you will know we have the 2d domain matrix and the 2d output matrix where the
domain value corresponds to its amplitude at the same position.
Now we add a for loop which find each domain value from the 2d domain matrix and
matches it with the corresponding output value and keeps adding it to the final 1d range
output. Now a single domain value might be repeated so we need a for loop to iterate through
the array and add all those components and put it inside the output array.
ii. Test your function on the signal and the impulse response provided in the figures below and
verify the correctness of your function through a comparison of manual computation of the
convolution for the given signal and a plot of your function’s output.
h[n]
5
0
-1 0 1 2 3 4 5
n
x[n]
5
0
-1 0 1 2 3 4 5 6
n
iii. MATLAB has a built-in function ‘conv’ that performs the same operation. Compare the results
of part (ii) with the conv function of MATLAB.
Code: main.m
%user inputs domain_1 =
[0 1 2 3 4 5]; domain_2 =
[0 1 2 3]; x_1 = [0 1 2 4
1 1]; h = [1 2 1 2];
[output_x, output_y] = myconv2(domain_1, x_1,domain_2, h); output
= conv(x_1,h);
subplot(2,2,1)
stem(domain_1,x_1, LineWidth=2) title("x[n]")
grid on
subplot(2,2,2)
stem(domain_2,h,LineWidth=2)
title("h[n]") grid on
subplot(2,2,3)
stem(output_x, output_y,LineWidth=2)
title("using my myconv") grid on
subplot(2,2,4)
stem(output, color='r',LineWidth=2)
title("using matlab conv") grid on
Output
iv. Consider now that x[n] starts from n = -1 and h[n] starts from -2. What will be the result of
convolution then? Plot the corresponding output signal using the stem command and proper
timing axis.
Domain changes to the output
domain_1 = [-1 0 1 2 3 4];
domain_2 = [-2 -1 0 1];
x_1 = [0 1 2 4 1 1];
h = [1 2 1 2];
output
CONCLUSION:
In this Lab experiment we revised the fundamentals of signals and systems with MATLAB and
came across Signal transformations. We also learnt the Even and Odd parts of a signal and once
again we get familiar with Convolution operator. For better understanding, we performed some
tasks and grab the complete concepts