SN Slab Manual
SN Slab Manual
Lab Manual
List of Experiments
Lab.no Experiment
Lab 01 Introduction to MATLAB.
Lab 02 Introduction to Script and Function Files, Loops and Conditional Statements.
Lab Sessional-I.
Lab Sessional-II.
Lab Final.
Electrical & Computer Engineering Dept.
The “MATLAB” name is obtained by combining the initials corresponding to MATrix LABoratory.
For detailed information regarding MatLab refer to www.mathworks.com.
Windows: There are several window types. The desktop includes the main windows corresponding to the
MATLAB core. However, in a typical session several secondary windows are opened and closed in order
to show figures, user interfaces, variable and file editors, SIMULINK models and libraries… Also,
specific windows exist for both the help and demos.
o Workspace.
o Command Window
Work space shows all
variables in use
1
Electrical & Computer Engineering Dept.
o Command History
Variables: Constitute the temporary objects (when the user exits MATLAB, all variables are deleted) and
they are stored in the so-called workspace.
Working with scalars
Variables are assigned numerical values by typing the expression directly in command window
(for beginners), for example, typing
2
Electrical & Computer Engineering Dept.
a = 1+2
yields: a = 3
The answer will not be displayed when a semicolon is put at the end of an expression. However,
the variable will be assigned value and can be viewed in workspace, for example type a = 1+2;.
i sqrt(-1)
j sqrt(-1)
pi 3.1416...
Example:
y= 2*(1+4*j)
yields: y = 2.0000 + 8.0000i
In order to view complex number use compass command, for more details use help command.
3
Electrical & Computer Engineering Dept.
b = [v a];
creates the vector b = [1 3 5 7 8 9 10].
The second method is used for creating vectors with equally spaced elements:
t = 0:0.1:10;
creates a 1x101 vector with the elements 0, .1, .2, .3,...,10. Note that the middle number defines the
increment. If only two numbers are given, then the increment is set to a default of 1:
k = 0:10;
creates a 1x11 vector with the elements 0, 1, 2, ..., 10.
Matrices are defined by entering the elements row by row:
M = [1 2 4; 3 6 8];
124
creates the matrix 𝑀 =
368
There are a number of special matrices that can be defined:
null matrix: M = [ ];
n x m matrix of zeros: M = zeros(n,m);
n x m matrix of ones: M = ones(n,m);
n x n identity matrix: M = eye(n);
An element of a matrix can be assigned:
M(1,2) = 5;
Places the number 5 in the first row, second column.
Operations and functions that were defined for scalars in the previous section can also be used on vectors
and matrices.
Example:
a = [1 2 3];
b = [4 5 6];
c = a + b
yields:
c= 5 7 9
Functions are applied element by element.
Example:
t = 0:10;
x = cos(2*t);
creates a vector x with elements equal to cos(2t) for t = 0, 1, 2, ..., 10.
Operations that need to be performed element-by-element can be accomplished by preceding the
operation by a ".". For example, to obtain a vector x that contains the elements of x(t) = tcos(t) at specific
points in time, you cannot simply multiply the vector t with the vector cos(t). Instead you multiply their
elements together:
t = 0:10;
x = t.*cos(t);
4
Electrical & Computer Engineering Dept.
Instruction Definition
Who Displays variables in the workspace
Whos Displays variables in the workspace with more details
Input function displays a prompt string in the command window and then waits for the user to type in a
response. For example, consider the following statement:
My_val=input(‘enter an input value’);
5
Electrical & Computer Engineering Dept.
Task:
i. Set up the matrix, 3×3. Interchange the 2nd and 3rd rows.
ii. Explore compass, legends and hold commands using help and plot any five complex numbers on one
compass figure. Each complex number should be represented with a different color and legends
should express the name of every complex number.
iii. Plot the given Complex number on compass diagram given at right hand side
𝑗𝜋
3. 0.9+j3
1. 2𝑒 4
4. 5 < −120
2. 5 − 𝑗6
6
90
8
120 60
150 4 30
180 0
210 330
240 300
270
Hand work
7
Electrical & Computer Engineering Dept.
Lab 2: “Introduction to Loops and M files in MatLab”
M-Files
While working in command window we normally face two very excruciating issues:
1. In case of any error we need to retype all our code again.
2. Even if you do not make any mistakes, all of your work may be lost if you inadvertently quit
MATLAB.
In order to overcome above mentioned issues and to preserve large sets of commands, you can store them
in a special type of file called an M-file. MATLAB supports two types of M-files:
1. Script
2. Function.
1) Scripts:
To hold a large collection of commands, we use a script M-file. The script file has a '.m' extension and is
referred to as an M-file (for example, myfile.m myfuncion.m, etc.). The commands in the script file can
then be executed by typing the file name without its extension in the command window or by clicking
To make a script M-file, you need to open a file using the built-in MATLAB editor. There are two ways
to accomplish it:
1. From file menu, click NEW
8
Electrical & Computer Engineering Dept.
When you are finished with typing in this new window, click File->Save to save this file. The extension
of this file will be “.m”. To execute this program,
1. Write the name of file on command window (excluding the .m), the name of the file must be
saved using the following instructions.
a. The name must be started with an alphabet and can later be followed by a digit as per
choice.
b. Only one special character can be used in the naming of the file i.e. “under the score” „_‟
c. There should be no spaces in the name, else an error may occur while running the file.
2. Click Debug->Run or press F5.
Example:
Let‟s make a script to execute the commands
>>x=10;
>>y=20;
>>z=x+y
First of all go to File->New->Script
An editor will be opened.
Then write the above command in the editor as shown below:
9
Electrical & Computer Engineering Dept.
2) FUNCTIONS
A function is a reusable portion of code that can be called from program to accomplish some specified
task. A function takes some input arguments and returns some output.
What do I have to put on the First Line of a MATLAB function?
The 1st line of a function must contain the “function definition,” which has a general structure like this:
function [Out_1,Out_2,…,Out_N] = function_name(In_1,In_2,…,In_M)
where Out_1,Out_2,…,Out_N are the N output variables and In_1,In_2,…,In_M are the M input
variables;
10
Electrical & Computer Engineering Dept.
You see that the sum z is displayed in the command window. Now go back to the editor/debugger and
modify the program as follows
function addv(x,y)
z=x+y
Save the above program with a new name addv, go back to the command window and type the following
» addv(3,5)
z =
8
» addv(5,5)
z =
10
We have actually created a function of our own and called it in the main program and gave values to the
variables (x,y).
Save the program with the same name addv, go back to command window, type the following
» help addv
This function takes two values as input,
finds its sum, & displays the result.
inputs: x & y
output: z
Example: addv(3,6)
11
Electrical & Computer Engineering Dept.
Result: z=9
SCRIPT VS FUNCTION
A script is simply a collection of Matlab commands in an m-file. Upon typing the name of the file
(without the extension), those commands are executed as if they had been entered at the
keyboard.
Functions are used to create user-defined matlab commands.
The commands in the script can refer to the variables already defined in Matlab, which are said to
be in the global workspace.
When a function is invoked, Matlab creates a local workspace. The commands in the function cannot
refer to variables from the global (interactive) workspace unless they are passed as inputs. By the same
token, variables created as the function executes are erased when the execution of the function ends,
unless they are passed back as outputs.
CONTROL STRUCTURES
Control-of-flow in MATLAB programs is achieved with logical/relational constructs, branching
constructs, and a variety of looping constructs.
Operator Description
===================================
< less than
> greater than
<= less than or equal
>= greater than or equal
== equal
~= not equal.
===================================
Note that ``='' is used in an assignment statement while ``=='' is used in a relation.
Relations may be connected or quantified by the logical operators
Operator Description
===================================
& and
| or
~ not.
===================================
12
Electrical & Computer Engineering Dept.
When applied to scalars, a relation is actually the scalar 1 or 0 depending on whether the relation is true or
false (indeed, throughout this section you should think of 1 as true and 0 as false). For example
>> 3 < 5
ans =
1
>> a = 3 == 5
a =
0
When logical operands are applied to matrices of the same size, a relation is a matrix of 0's and 1's giving
the value of the relation between corresponding entries. For example:
>> A = [ 1 2; 3 4 ];
>> B = [ 6 7; 8 9 ];
>> A == B
ans =
0 0
0 0
>> A < B
ans =
1 1
1 1
To see how the other logical operators work, you should also try
>> ~A
>> A&B
>> A & ~B
>> A | B
>> A | ~A
Branching constructs
MATLAB provides a number of language constructs for branching a program's control of flow.
i. if-end Construct : The most basic construct is:
if <condition>,
<program>
end
Here the condition is a logical expression that will evaluate to either true or false (i.e., with values 1 or 0).
When the logical expression evaluates to 0, the program control moves on to the next program
construction. You should keep in mind that MATLAB regards A==B and A<=B as functions with values
0 or 1.
Example :
>> a = 1;
>> b = 2;
>> if a < b,
c = 3;
end;
>> c
13
Electrical & Computer Engineering Dept.
c =
3
ii. If-else-end Construct: Frequently, this construction is elaborated with
if <condition1>,
<program1>
else
<program2>
end
In this case if condition is 0, then program2 is executed.
14
Electrical & Computer Engineering Dept.
Example: MATLAB will allow you to put any vector in place of the vector 1:n in this construction. Thus
the construction
>> for i = [2,4,5,6,10],
<program>,
end
is perfectly legitimate.
In this case program will execute 5 times and the values for the variable i during execution are
successively, 2,4,5,6,10.
i. While Loops
A while loop is a construction of the form
while <condition>,
<program>,
end
where condition is a MATLAB function, as with the branching construction. The program will execute
successively as long as the value of condition is not 0. While loops carry an implicit danger in that there is
no guarantee in general that you will exit a while loop. Here is a sample program using a while loop.
function l=twolog(n)
% l=twolog(n). l is the floor of the base 2
% logarithm of n.
l=0;
m=2;
while m<=n
l=l+1;
m=2*m;
end
TASK:
3𝜋
1. Generate a function that returns you 𝐴cos ( 7 𝑡 + 𝑡𝑜 ), and its inputs are A, t, and 𝑡𝑜 .
2. Also, the function when gets executed, it should ask you whether you want to continue or not. If
yes, the main program script should ask you for input A, t and 𝑡𝑜 , else it should exit MatLab.
3. Write a function that takes any size of matrix as input and returns the transpose of that matrix.
Implement the logic of transpose using for loop. Don‟t use direct function.
15
Electrical & Computer Engineering Dept.
GRAPHICS
MATLAB has an excellent set of graphic tools. Plotting a given data set or the results of computation is
possible with very few commands. You are highly encouraged to plot mathematical functions and results
of analysis as often as possible. Trying to understand mathematical equations with graphics is an
enjoyable and very efficient way of learning mathematics. Being able to plot mathematical functions and
data freely is the most important step, and this section is written to assist you to do just that.
Two- and three-dimensional MATLAB graphs can be given titles, have their axes labeled, and have text
placed within the graph. The basic functions are:
Function Description:
plot(x,y) plots y vs x
plot(x,y1,x,y2,x,y3) plots y1, y2 and y3 vs x on the same graph
stem(x) plots x and draws a vertical line at each
data point to the horizontal axis
stairs(x) draws a stairstep graph of the elements of vector x.
xlabel('x axis label') labels x axis
ylabel('y axis label') labels y axis
title ('title of plot') puts a title on the plot
gtext('text') activates the use of the mouse to position a
Cross hair on the graph, at which point the
'text' will be placed when any key is pressed.
zoom allows zoom IN/OUT using the mouse cursor
grid draws a grid on the graph area
print filename.ps saves the plot as a black and white postscript
file
shg brings the current figure window forward.
CLF clears current figure.
>> x=0:0.1:2*pi;
>> y=sin(x);
>> plot(x, y);
16
Electrical & Computer Engineering Dept.
Here we are plotting the values of y along (y-axis) versus the values of x along (x-axis). The result of this
command is shown in Figure below
Two-dimensional plots
The plot/stem command creates linear x-y plots; if x and y are vectors of the same length, the command
stem(x,y)/plot(x,y) opens a graphics window and draws an x-y plot of the elements of x versus the
elements of y.
Example: Let's draw the graph of the discrete unit step function, using different methodologies.
Method-I:
17
Electrical & Computer Engineering Dept.
DT unit-impulse signal can also be implemented using ones( ) and zeros( ) functions.
Method-II:
Sign function: Y = sign(X)
Y = sign(X) returns an array Y the same size as X. For each element of X, sign(X) returns 1 if the element
is greater than zero, 0 if it equals zero and -1 if it is less than zero.
>>n=-10:10;
>>unit=(sign(n+eps)+1)/2;
>>stem(n,unit); title 'Unit Step function', axis([-10 10 -2 2]);
>> xlabel 'samples',ylabel 'u[n]'
Method I
>>t=-2:0.01:2;
y=heaviside(t);
subplot(211),plot(t,u),axis([-2.5 2.5 -1 1.5])
title 'Plotting Unit Step using Heaviside Command'
xlabel 'time',ylabel 'y(t)'
We are introducing the concept of subplots here that is how we divide a single figure into multiple plots.
Further details will be provided by the instructor or MatLab command window can be used by typing
‘help subplot’.
Method II
t=-5:0.01:5;
u=0.*(t<=0)+1.*(t>0);
subplot(212),plot(t,u)
xlabel('Samples'),ylabel('u(t)'),title('Plotting Unit Step using
if/else concept')
grid on
axis([-6 6 -1 2])
18
Electrical & Computer Engineering Dept.
19
Electrical & Computer Engineering Dept.
Three-dimensional plots
The plot3 command creates linear x-y-z plots;if x, y and z are vectors of the same length, the command
plot3(x,y,z) opens a graphics window and draws an x-y-z plot of the elements of y & z versus the
elements of x.
Example: Let's draw a 3D Spiral
t=-10:0.1:10;
x=cos(2*pi/3*t);y=sin(2*pi/3*t);
plot3(t,x,y)
20
Electrical & Computer Engineering Dept.
TASK:
Make the given unit step a function. Then generate another function by the name of unit_impulse, that
generates a unit impulse signal. Now execute the following equation using both functions described
above.
2𝜋
𝑥 𝑡 = cos 𝑡 𝑢 𝑡 + 5𝛿 𝑡 − 9𝛿 𝑡 − 9 ; −20 < 𝑡 < 20
3
Taking help from above given codes, design a new code that generates the following equations and also
shows its 3D, real, imaginary, phase and magnitude plots. 𝑥 𝑡 = (0.6𝑒 𝑗 7/4𝜋 )𝑡 &𝑦 𝑡 = (7/3𝑒 𝑗 7/4𝜋 )𝑡
21
Electrical & Computer Engineering Dept.
In this lab the students will be able to implement the Linear transformation of independent variable i.e.,
time shift, time scaling and time reversal operations on continuous time (CT) signals and discrete time
(DT) signals.
Introduction:
An important concept in signal and system analysis is the transformation of a signal. In this section three
elementary transformation are performed on a signal in the time domain. These transformations are time
shifting, time scaling, and time inversion.
Time Shifting
The time-shifting operation delays or advances forward the input signal in time. Consider a CT signal y(t)
obtained by shifting another signal x(t) by T time units. The time-shifted signal y(t) is expressed as
follows:
𝒚(𝒕) = 𝒙(𝒕 + 𝑻)
Suppose a signal x(t) is given as
𝒙(𝒕) = 𝒆−𝒕 𝒖(𝒕)
To determine the expression for x(t-4), substitute t by (t - 4). The resulting expression is given by
clear all
close all
clc
22
% Above figure 4.4 (Oppenhiem 2nd Edition)
t0=-2;%%Shift data by t0<0 (L.H.S)
x2=heaviside(t-t0).*exp(-(t-t0));%for shifting t we add -t0 to t
subplot(223),plot(t,x2),title(['x(t-(' num2str(t0) '))']),xlabel 't',ylabel
'Amplitude'
x4=(heaviside(t+1)-heaviside(t)).*(t+1)+…
(heaviside(t)-heaviside(t-2))+(heaviside(t-2)-heaviside(t-3)).*(-t+3);
subplot(311),plot(t,x4),title 'Signal by parts:: x(t)',xlabel 't'
ylabel 'Amplitude'
grid on, axis([-4 12 -1 1.5])
23
grid on, axis([-4 12 -1 1.5])
Tasks
Perform the given transformations on x(t) given as
24
Electrical & Computer Engineering Dept.
In this lab, you will learn about the Symbolic Math Toolbox provided in MatLab. Symbolic Math
toolbox provides functions for solving and manipulating symbolic math expressions and performing
variable-precision arithmetic. You can analytically perform differentiation, integration, simplification,
transforms, and equation solving. A book is also uploaded on the course portal. Refer to the book for
details. The following topics will be discussed in the lab:
Creating Symbolic Variables and Expressions Integration
Creating Symbolic Math Functions Indefinite Integral
Differentiation Definite Integral
Symbolic and Numeric Conversions Symbolic Summation
Limits Solution of Equations
ans = 27
For the details of subs command, read page 21 of the bookSymbolic MathToolbox.
25
Electrical & Computer Engineering Dept.
d 2f
MATLAB can take higher order differentials. For example, to find diff2_f = we do
dx 2
>>diff2_f=diff(f,x,2) using the already defined expression for f.
5)Limits
26
Electrical & Computer Engineering Dept.
The fundamental idea in calculus is to make calculations on functions as a variable “gets close to” or
approaches a certain value.
For example
sin( ax)
lim
x 0
x
clear;
syms x a;
value = limit(sin(a*x)/x,x,0)
value =
a
value= limit(sin(x)/x,x,0)
value =
1
6) Integration:
If f is a symbolic expression, then
int(f)
attempts to find another symbolic expression, F, so that diff(F) = f. That is, int(f) returns the
indefinite integral or antiderivative of f (provided one exists in closed form). Similar to differentiation.
Indefinite integrals: For the syntax for symbolic integration, see >>help sym/int. Thus, for
example, to find the indefinite integral
int_g = gdx where g = e-axsin(cx),
We do
clear;
syms a c x;
g=exp(-a*x)*sin(c*x);
27
Electrical & Computer Engineering Dept.
int_g = int(g,x)
Check this by taking
>>diff_int =diff(int_g,x)
This should give back g, but it doesn’t look the same because MATLAB doesn’t always give things in the
simplest format. In this case, we again use the simple command
>>diff_int_simp = simple(diff_int)
Note that MATLAB does not add the constant of integration (“C”) customarily shown for indefinite
integrals -- this you must do by adding C after the int command.
Sometimes MATLAB is not able to integrate an expression symbolically. For example, try to find fdx
(where, as before, f = 𝑒 −ax 𝑥 3𝑏 sin(cx) and a, b and c are unspecified constants).
clear;
symsa b c x;
f = exp(-a*x)*x^(3*b)*sin(c*x);
int(f,x)
When MATLAB cannot find a solution, it gives a warning message and repeats the command. When this
happens, you’re out of luck.
Definite integrals: For the definite integral, int_def_g =
gdx
Enter
clear;
syms a c x;
g = exp(-a*x)*sin(c*x);
int_def_g = int(g,x,-pi,pi)
1. Create the function to be integrated in the MATLAB editor and save it to your Current Directory,
which must also be in the path (File / Set Path). For example, for our exp(sin(x)) function:
function out = func1(x)
out = exp(sin(x));
end
2. Use either one of the following formats:
>>quad('func1',0,1)
28
Electrical & Computer Engineering Dept.
or
>>quad(@func1,0,1)
Note: For details on Integration page 38-45 of the book
7)Symbolic Summation:
You can compute symbolic summations, when they exist, by using the symsumcommand. For example,
the p-series
syms x k
s1 = symsum(1/k^2,1,inf)
s2 = symsum(x^k,k,0,inf)
s1 =
1/6*pi^2
s2 =
-1/(x-1)
Note:For Taylor Series and other details read Page 45-47
8) Solution of Equations:
The symbolic toolbox in MATLAB is capable of solving many types of equations, including non-linear
ones and several simultaneous equations. See >> help solve. The steps in solving one or more equations
using “solve” are:
Step 1: Define the variables in the equations as symbolic using the “syms” command.
Step 2: Define the equations (see the examples below).
Step 3: Solve the equations using the “solve” command.
Step 4: If there is more than one solution, decide which is physically reasonable and select it.
Step 5: Check the solution by substituting it back into the original equation(s).
29
Electrical & Computer Engineering Dept.
Example:
clear all;
clc;
syms x y z a b c;
eq = 'a*x^2+b*x+c = 0';
[x]=solve(eq,x)
(Note that single quotation marks must be placed around an equation that is assigned to a variable, here
eq.) As expected, we obtain two solutions.
x =
-(b + (b^2 - 4*a*c)^(1/2))/(2*a)
-(b - (b^2 - 4*a*c)^(1/2))/(2*a)
Suppose we want only the first. This is extracted by
>>x1 = x(1)
This should be done manually or using a logical operator (“if” command), because MATLAB's symbolic
engine doesn't always give multiple solutions in the same order. What is x(1) now could be x(2) in a
subsequent trial.
Example:
Find the solution to e2x=3y:
clear all;
clc;
syms x y;
eq = 'exp(2*x) = 3*y';
[x] = solve(eq,x)
We use a similar procedure to solve simultaneous equations. First, let us look at a set of linear equations,
and then non-linear equations.
Example:
Find the solution to the following set of linear equations:
2x-3y+4z = 5
y+4z+x = 10
-2z+3x+4y = 0
syms x y z;
eq1 = '2*x-3*y+4*z = 5' ;
eq2 = 'y+4*z+x = 10' ;
eq3 = '-2*z+3*x+4*y = 0' ;
[x,y,z] = solve(eq1,eq2,eq3,x,y,z)
30
Electrical & Computer Engineering Dept.
Notice that we did not have to enter x, y and z in any particular order in defining the equation variables
(unlike the numerical MATLAB method using matrices with \ or inv). However, the variables in the
output are in alphabetical order, regardless of how they are written in the command. So take care to list
the variables in the brackets in alphabetical order. (For example, if you use [z,x,y] rather than [x,y,z] in
the above example the result produced for z is actually x, that for x is actually y, and that for y is actually
z.) Again, the results may be symbolic and require conversion to numeric form for subsequent
calculations:
NOTE: It is a self-study practical However, coming 3 to 4 labs are based on this lab, therefore, special attention should be
paid to this lab.
Symbolic and Numeric Conversions
Char Convert symbolic objects to strings
TASK
Find energy and power of the given signals using Symbolic Math Toolbox.
i) x(t)=2 Sin(t) ii) x[n]= cos(3πn)
31
Electrical & Computer Engineering Dept.
clc
clear
close all
n=-100:100;
u=(sign(n+eps)+1)/2;%unit step u[n]
u1=(sign(n-21+eps)+1)/2;%unit step u[n-21]
h=u-u1;%impulse response of system (h[n]=u[n]-u[n-21])
x=u.*exp(-3/20*n);%input x[n]
subplot(211),stem(n,h), title 'Impulse Response'
xlabel 'Samples--n',ylabel 'h[n]'
subplot(212),stem(n,x),title 'Input'
xlabel 'Samples--n',ylabel 'x[n]'
h[n]
x[n]
32
Electrical & Computer Engineering Dept.
y[n]=h[n]*x[n]
For same length of input/output we can use the same conv command but with some edited parameters, as
given below:
y=conv(h,x,'same');
figure,stem(n,y),title 'convolution using built-in function'
xlabel 'Samples--n',ylabel 'y[n]=h[n]*x[n]'
In this case we do not need to fix the sample axis ‘n’ and the same samples can be used as in initial
definition, the output is as given below:
y[n]=h[n]*x[n]
%Method 2
%Convolution Step by Step
33
Electrical & Computer Engineering Dept.
n=-50:50;
%%%Flip
xn_k=exp(-0.5*(-k+n0)).*(unit(-k+n0));%replacing k by -k
y=zeros(size(n));
for i=1:length(n)
y1=exp(-0.5*(-k+n(i))).*(unit(-k+n(i)));
subplot(311)
stem(n,h);
hold on; stem(n,y1,'r');hold off
title(['h[n] & x[n-(' num2str(n(i)) ')']);
y1=y1.*h;
subplot(312),stem(n,y1)
y(i)=sum(y1);title(['Product of h[n]&h[n-(' num2str(n(i)) ')']);
subplot(313),stem(n,y),title 'convoluted y[n]'
waitforbuttonpress% if you wana see a step by step output
end
0.5
0
-50 0 50
10 -7 Product of h[n] & x[n-(50)]
4
0
-50 0 50
convoluted y[n]
4
0
-50 0 50
34
Electrical & Computer Engineering Dept.
Convolution Integral:
Convolution Integral means convolution of two CT signals. We have discussed it in much detail in the
class. Now it’s time to implement it in Matlab so that you could sharpen your concepts.
I will say few words about the CT convolution just to refresh the concepts.
Convolution helps to determine the effect of the system on an input signal. The shifting property of
impulses tells us that a signal can be decomposed into an infinite sum (integral) of scaled and shifted
impulses. Knowing how a system affects a single impulse, and by understanding the way a signal is
comprised of scaled and summed impulses, it seems reasonable that it should be possible to scale and sum
the impulse responses of a system in order to determine what output signal will results from a particular
input.
Example 1:
Compute the convolution integral y(t)=x(t)*h(t) of the following pairs of signals:
𝑥 𝑡 = 𝑒 −3𝑡 𝑢 𝑡
ℎ 𝑡 =𝑢 𝑡+3
35
Electrical & Computer Engineering Dept.
Task:
Compute the convolution integral, using the same strategy as implemented in lab 6
y(t)=x(t)*h(t) of the following pairs of signals:
36
Electrical & Computer Engineering Dept.
Fourier analysis:
In mathematics, Fourier analysis is the study of the way general functions may be represented or
approximated by sums of simpler trigonometric functions the subject of Fourier analysis
encompasses a vast spectrum of mathematics. In the sciences and engineering, the process of
decomposing a function into simpler pieces is often called Fourier analysis, while the operation
of rebuilding the function from these pieces is known as Fourier synthesis.
Example:
Fourier Analysis of a square wave (Check example 3.5 of the book for detail)
Code:
clc
clear all
close all
T=4*T1;
w=2*pi/T;%omega
a=[subs(ak,k,-N:-1) a0 subs(ak,k,1:N)];
stem(-N:N,a)
Fourier Synthesis
Let us implement the synthesis equation i.e. add the Fourier components as follows:
x(t) = a0
37
Electrical & Computer Engineering Dept.
.
.
Until we get a close approximated shape of x (t).
%Fourier Sythesis
for k1=1:N
x=x+d(N+1+k1)*(exp(1i*k1*w0*t)+exp(-1i*k1*w0*t));
ezplot(t,x);
waitforbuttonpress
end
Results:
1.2 1.2
1 1
0.8 0.8
0.6 0.6
0.4 0.4
0.2
0.2
0
0
-0.2
-0.2 -1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
1 1
0.8 0.8
0.6 0.6
0.4 0.4
0.2 0.2
0 0
-0.2 -0.2
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1 -1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
38
Electrical & Computer Engineering Dept.
1.2
1.2
1
1
0.8
0.8
0.6
0.6
0.4
0.4
0.2
0.2
0
0
-0.2
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
-0.2
N=50 Harmonics -1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
N=200 Harmonics
Task:
Implement a complete harmonic set for Triangular wave.
39
Electrical & Computer Engineering Dept.
Lab 09: “Continuous Time Fourier Transform & Discrete Time Fourier Transform
Implementation in MatLab”
The basic objective of this Lab is to make the students familiar with Fourier transform fusing MatLab. In
MatLab a built-in function for ‘fft’ exists which is the implementation of Fast Fourier transform;
however, there is no function available for CTFT.
function [w,X]=CTFT(t,x)
w= -pi:0.01:pi;
ee=exp(-j*w'*t);
w=w./pi*1000;
X=x*ee';
DFT:
The basic objective of this Lab is to make the students familiar with Discrete Fourier transform using
MatLab. In MatLab a built-in function for fft exists, however, there is no function available for DTFT.
40
Electrical & Computer Engineering Dept.
15. Now make another M-File that would act as the calling module, save it by any useful name
but remember not to start the name by any numeric digit, do not use any special character
other than under-the-score ( _ ) and also remember not to give any space in the name.
16. Previously, generated unit step function would be quite a help in this Lab.
Example:
close all;
clc
clear
n=-100:100;
unit=(sign(n+eps)+1)/2;
g=(sign(n-7+eps)+1)/2;
h=(1/7)*(unit-g);
[w,H]=F_DtFt(n,h);
w=w./pi;
figure,subplot(3,1,1),stem(n,h);ylabel 'h[n]',xlabel 'n (samples)'
subplot(3,1,2),plot(w,abs(H));ylabel '|H(e^{j\omega})|'
xlabel '\omega (Multiple of \pi)'
subplot(3,1,3),plot(w,angle(H));ylabel '\angle H(e^{j\omega})'
xlabel '\omega (Multiple of \pi)'
a=sin((pi/3)*n)./(pi*n);
x=[a(1:100) 1 a(102:201)];
figure,subplot(3,1,1),stem(n,x);title 'x[n]'
[w,X]=F_DtFt(n,x);
subplot(3,1,2),plot(w,abs(X));ylabel '|X(e^{j\omega})|'
subplot(3,1,3),plot(w,phase(X));ylabel '\angle X(e^{j\omega})'
N=[2*n(1,1):2*n(1,length(n))];
y=conv(x,h);
figure,stem(N,y);title 'y[n]'
[w,Y]=F_DtFt(N,y);
subplot(2,1,1),plot(w,abs(Y));ylabel '|Y(e^{j\omega})|'
title 'By convolution'
subplot(2,1,2),plot(w,phase(Y));ylabel '\angle Y(e^{j\omega})'
figure
Y1=X.*H;
subplot(2,1,1),plot(w,abs(Y1));ylabel '|Y(e^{j\omega})|'
title ' By Multiplication'
subplot(2,1,2),plot(w,phase(Y1));ylabel '\angle Y(e^{j\omega})'
Calling Function:
function [w,X]=F_DtFt(n,x);
w=-20:0.01:20;
e=(exp(j*w'*n))';
X=x*e;
41
Electrical & Computer Engineering Dept.
Output:
42
Electrical & Computer Engineering Dept.
43
Electrical & Computer Engineering Dept.
Learning Objectives: At the end of this lab the students will be able to learn
We want to read the digital sound data from the .wav file into an array in our MATLAB workspace.
We can then listen to it, plot it, manipulate, etc. Use the following command at the MATLAB prompt
44
Electrical & Computer Engineering Dept.
The array guitar now contains the stereo sound data and fs is the sampling frequency. This data is
sampled at the same rate as that on a music CD (fs=44,100 samples/second).
Channels:
The left and right channel signals are the two columns of the road array:
left_guitar=guitar(:,1);
right_guitar=guitar(:,2);
Let’s plot the left data versus time. Note that the plot will look solid because there are so many
data points and the screen resolution can’t show them all. This picture shows you where the signal is
strong and weak over time.
time=(1/44100)*length(left_guitar);
t=linspace(0,time,length(left_guita
r)); plot(t,left_guitar);
xlabel('time (sec)');
Let’s plot a small portion so you can see some details
time=(1/44100)*2000;
t=linspace(0,time,2000);
plot(t,left_guitar(1:2000))
xlabel('time (sec)');
ylabel('relative signal strength')
45
Electrical & Computer Engineering Dept.
Listening to Guitar
Let’s listen to the data (plug in your headphones). Click on the speaker icon in the lower right hand
corner of your screen to adjust the volume. Enter these commands below one at a time. Wait until the
sound stops from one command before you enter another sound command!
Reverse Playing
To play the sound backwards, we simply reverse the order of the numbers in the arrays. Let’s
experiment with a small array. Type in the following commands:
y=[1;2;3;4;5]
y2=flipud(y)
Note that flipud stands for flip upside-down which flips your array y and stores the inverted array in a
new array called y2.
left2=flipud(left_guitar);
soundsc(left2,fs)
Digital Delay Experiment 1:
Now let's add an echo to our sound data by adding to each sound sample, the sample from a previous
time:
leftout(n)=left_guitar(n)+left_guitar(n-N); % approximately ¼
second echo end
Note that these arrays are large and it may take some time for the processing to be completed.
Compare the input and output by typing the following after the cursor returns, indicating that the
processing is done:
soundsc(left_guitar,fs) % original
% Wait until the sound stops before moving to next sound
command soundsc(leftout,fs) % signal with new echo
46
Electrical & Computer Engineering Dept.
This program first sets the output to be the input. This is simply a quick way to initialize the output
array to the proper size (makes it operate faster). The loop starts at n=10001 and goes up to the full
length of our array left_guitar. The output is the sum of the input at sample time n plus the input at
sample time n-10000 (10000 samples ago, 10000/44100 seconds ago since the samples are spaced by
1/44100 seconds). Try some different delay amounts.
Try it in stereo and we will echo left-to-right and right-to-left!
out=guitar; % set up a new array, same size as old one
N=10000; % delay amount N/44100
seconds for n=N+1:length(guitar)
out(n,1)=guitar(n,1)+guitar(n-N,2); % echo right-
to-left! out(n,2)=guitar(n,2)+guitar(n-N,1); % echo left-
to-right!
end
soundsc(guitar,fs) % original
soundsc(guitar,fs) % echo
out=guitar;
for n=2:length(guitar)
out(n,1)=.9*out(n-1,1)+guitar(n,1); % left
out(n,2)=.9*out(n-1,2)+guitar(n,2); % right
end
Compare the input and output as before. Note that the modified signal sounds muffled in comparison
to the input data. This is because the high frequency components have been suppressed in the output
soundsc(guitar,fs) % original
A small change in our digital filter allows us to boost high frequencies and suppress low frequencies:
47
Electrical & Computer Engineering Dept.
out=guitar;
for n=2:length(guitar)
out(n,1)=guitar(n,1)-guitar(n-1,1); % left
out(n,2)=guitar(n,2)-guitar(n-1,2); % right
end
The sampling frequency fs tells us how much time goes between each sample (T=1/fs). If we play the
song with more or less time between samples than was originally there when recorded, the speed will
seem off, producing interesting effects...
In most popular music recordings, the vocal track is the same on the left and right channels (or very
similar). The volume of the various instruments is more unevenly distributed between the two
channels. Since the voice is the same on both channels, what would happen if we subtract one channel
from the other and listen to the result?
Note the above code may not for a song that uses a stereo reverberation effect and the echo moves
back and forth between left and right channels (like our stereo delay above). This makes the voice
unequal from left to right channels.
48
Electrical & Computer Engineering Dept.
Guitar:
function [ ] = guitar_analysis( )
[guitar,fs] = wavread('guitar.wav');
%Time plot
time=(1/fs)*length(guitar);
t=linspace(0,time,length(guitar));
subplot(2,1,1);
plot(t,guitar);
title('Guitar');
xlabel('time (sec)');
nfft = 2^nextpow2(length(guitar));
sound_spec = fft(guitar,nfft)/sqrt(nfft);
subplot(2,1,2);
plot(frange,2*abs(sound_spec(1:nfft/2+1)));
xlabel('frequecny(Hz)');
ylabel('Magnitude of fft');
wavplay(guitar,fs);
end
49
Electrical & Computer Engineering Dept.
function [ ] = frequency_analysis( )
clc;
clear all;
fs=48000;
figure(1);
left_gz=a_gz(:,1);
time=(1/fs_gz)*length(left_gz);
t=linspace(0,time,length(left_gz));
subplot(3,1,1);
plot(t,left_gz);
xlabel('time (sec)');
subplot(3,1,2);
plot(t,left_basit); title('Basit
voice of saying a'); xlabel('time
(sec)');
50
Electrical & Computer Engineering Dept.
left_faryal=a_faryal(:,1);
time=(1/fs_faryal)*length(left_faryal);
t=linspace(0,time,length(left_faryal));
subplot(3,1,3);
plot(t,left_faryal);
xlabel('time (sec)');
figure(2);
nfft_gz = 2^nextpow2(length(left_gz));
nfft_basit = 2^nextpow2(length(left_basit));
nfft_faryal = 2^nextpow2(length(left_faryal));
sound_spec_gz = fft(left_gz,nfft_gz)/sqrt(nfft_gz);
sound_spec_basit = fft(left_basit,nfft_basit)/sqrt(nfft_basit);
sound_spec_faryal = fft(left_faryal,nfft_faryal)/sqrt(nfft_faryal);
51
Electrical & Computer Engineering Dept.
subplot(3,1,1);
plot(frange_gz,2*abs(sound_spec_gz(1:nfft_gz/2+1)));
xlabel('frequecny(Hz)');
ylabel('Magnitude of fft');
subplot(3,1,2);
plot(frange_basit,2*abs(sound_spec_basit(1:nfft_basit/2+1)));
xlabel('frequecny(Hz)');
ylabel('Magnitude of fft');
subplot(3,1,3);
plot(frange_faryal,2*abs(sound_spec_faryal(1:nfft_faryal/2+1)));
xlabel('frequecny(Hz)');
ylabel('Magnitude of fft');
end
Lab Tasks
Q.1. Record your voice using MATLAB. Plot the original signal and its frequency spectrum.
52
Electrical & Computer Engineering Dept.
Learning Objectives: At the end of this lab the students will be able to learn
How to read and display image in MATLAB.
How to find the RGB components of a color image.
Conversion from RGB to Grayscale.
Conversion from Grayscale to Binary image.
Image as a 2-Dimentional Signal:
An image is a two dimensional signal composed of two independent variables. Figure 10.1 shows how an
image data is stored in the form of matrix.
Visualization - Observe the objects that are not visible.
Image sharpening and restoration - To create a better image.
Image retrieval - Seek for the image of interest.
Measurement of pattern – Measures various objects in an image.
Image Recognition – Distinguish the objects in an image.
Myimage = imread(‘filename’);
53
Electrical & Computer Engineering Dept.
This command will save the image in the Image detail module. The command imread() is used in
MATLAB to store image file. An image is stored in MATLAB in the form of an image matrix. This
matrix contains the values of all the pixels in the image. In the case of a grayscale image, the image
matrix is a 2x2 matrix. In the case of a color image we have a 3x3 matrix.
After storing this image, you can view it using the command
imshow(Myimage);
Example:
InputImg = imread('sample.jpg');
imshow(InputImg)
MATLAB has the ability to find out exactly how much Red, Green, and Blue content there is in an
image. You can find this out by selecting only one color at a time and viewing the image in that color.
The following code allows you to view the Red content of an image:
54
Electrical & Computer Engineering Dept.
Similarly, we can do the same with the green and blue components of the image. Just keep in mind the
format of the array
1 2 3
Code
InputImg = Imread('sample.jpg');
figure
GImg = InputImg(:,:,1)
figure
figure
imshow(InputImgGray)
55
Electrical & Computer Engineering Dept.
Binary image is the image having only two values either zero or one. In gray scale image value of image
ranges from 0- 256 levels which are thresholded into two levels 0 or 1
clear all
inputImg = Imread('sample.jpg');
figure
GImg = inputImg(:,:,1);
figure
for i=1:Height
for j=1:Width
if GImg(i,j,1)>115
BinaryImg(i,j)=0;
else
BinaryImg(i,j)=1;
end
end
end
figure
56
Electrical & Computer Engineering Dept.
Lab Tasks
Q.1. Load given image and convert it into binary image. Display original image and binary
image.
57
Electrical & Computer Engineering Dept.
58