0% found this document useful (0 votes)
10 views60 pages

SN Slab Manual

Uploaded by

engrizhar9040
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views60 pages

SN Slab Manual

Uploaded by

engrizhar9040
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Signals & Systems

Lab Manual

Engr. Rabya Bahadur, Dr. Shadan Khattak, Dr. Shoaib Azmat


COMSATS UI Abbottabad Campus
Electrical & Computer Engineering Dept.

List of Experiments

Lab.no Experiment
Lab 01 Introduction to MATLAB.

Lab 02 Introduction to Script and Function Files, Loops and Conditional Statements.

Lab 03 Plotting of Continuous Time and Discrete Time Signals.

Lab 04 Transformation of Independent Variables.

Lab Sessional-I.

Lab 05 Introduction to Symbolic Math Toolbox.

Lab 06 Implementation of Convolution Sum.

Lab 07 Implementation of Convolution Integral.

Lab 08 Implementation of Fourier Series.

Lab 09 Implementation of Fourier Transform.

Lab Sessional-II.

Lab 10 Introduction to Speech Processing.

Lab 11 Introduction to Two Dimensional Signals (Image Processing.)

Lab Final.
Electrical & Computer Engineering Dept.

Lab 1: “Introduction to MATLAB”

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.

 Getting to know different windows:

o Workspace.
o Command Window
Work space shows all
variables in use

All executions are done in the command


window. All commands are written here
and different variables are formed

1
Electrical & Computer Engineering Dept.

o Command History

It gives you an incite about


the previously used
commands with date and
time

o Current Directory and directory path

Here we choose the folder


where we want our MatLab files
to stored and access from

In current directory we can


easily view all the folders and
MatLab files that we need to
access and all other related files
in that particular directory.

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;.

MATLAB utilizes the following arithmetic operators:


+ addition
- subtraction
* multiplication
/ division
^ power operator
' transpose
Example:
b = 2*a;
To determine the value of a previously defined quantity, type the quantity by itself:
b
yields: b = 6
If your expression does not fit on one line, use an ellipsis (three or more periods at the end of the line) and
continue on the next line.
c = 1+2+3+...
5+6+7;

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.

Working with matrices:


MATLAB is based on matrix and vector algebra; even scalars are treated as 1x1 matrices. Therefore,
vector and matrix operations are as simple as common calculator operations. Vector can be defined in two
ways.
The first method is used for arbitrary elements:
Example:
v = [1 3 5 7];
creates a 1x4 vector with elements 1, 3, 5 and 7. Note that commas could have been used in place of
spaces to separate the elements. Additional elements can be added to the vector:
v(5) = 8;
yields the vector v = [1 3 5 7 8].
Previously defined vectors can be used to define a new vector.
Example (with v defined above)
a = [9 10];

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.

Work space Management

Instruction Definition
Who Displays variables in the workspace
Whos Displays variables in the workspace with more details

Clear Deletes MATLAB workspace (all variables)


clear(„y‟) Deletes the variable named y

clear y Deletes the variable named y (another way)


Saves workspace variables to a storage device file named
save file_name “file_name.mat”
Loads workspace variables from a file of storage device named
load file_name “file_name.mat”

Command Window Management


Instruction Definition
clc Clears command window
x=1; „;‟ suppresses echo
UP ↑ & DOWN ↓ arrows Recall previously executed commands

Initializing variables with keyboard input:

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’);

Built-in constants in MATLAB


MATLAB has some built-in names for constants. Usually, it is a bad idea to overwrite the names of
built-in constants, i.e. to use names for our own variables/constants which coincide with built-in
MATLAB names. Some built-in MATLAB constants/names are shown in Table below.
Table: Some Built-In MATLAB Constants.
Name Math Name Value Description
i I Used in Mathematics
j j Used in Electrical Engineering
pi
-16
eps 2.2402 x 10 Smallest number in MATLAB > 0
inf e.g., 1/0
NaN e.g., 0/0, Not a Number

5
Electrical & Computer Engineering Dept.

Table: Built-In MATLAB Functions


Function Description
length(a) Gives you the length of the longer dimension.
Gives you the length of all the dimensions of the array
size(a) back as a n- element array).
length(a(:,1)) Gives you the length of the column
length(a(1,:)) Gives you the length of the row
size(a,n) Gives you the length of the nth dimension of a
a(end) Gives you the last element of the array
max(a) Gives the maximum number in each column
max(max(a)) Gives the maximum number in whole array
a(:) Linearize an array – in other words make the whole array into one column
max(a(:)) Gives the maximum number in whole array
min(a) Gives the minimum number in each column
floor(a) Rounds down to the nearest integer
ceil(a) Rounds up to the nearest integer
round(a) Rounds to the closest integer
Makes an array of dimension n where all value are zero except on the diagnol
a=eye(n) where they are equal to 1.
a=eye(m,n) Same as above except the array in m by n
a=zeros(m,n) Makes an array of zeros m by n
a=ones(m,n) Makes an array of ones m by n

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

„Run‟ icon or simply by pressing F5 button while „M-file‟ is open.


Commands in a script utilize and modify the contents of the current workspace. It is possible to embed
comments in a script file.

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.

2. Type edit on command line


A new window appears like one shown in the figure below.

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.

Now save it, let‟s say with the name script1.m.


Close the editor and go back to command window and write the script name as:
>>script1
Z =
30
You could also run the script from the editor window
Debug- Run or by pressing F5

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;

If there is only a single output variable use:


function Out_1 = function_name(In_1,In_2,…,In_M)

If there is no output variable use:


function function_name(In_1,In_2,…,In_M)

What do I have to put after the 1st line?


After the first line, you just put a sequence of MATLAB commands – with one command per line – just
like you are computing in MATLAB, in the command line environment. This sequence of commands is
what makes up your program – you perform computations using the input variables and other variables
you create within the function and in doing so, you create the output variables you desire.

10
Electrical & Computer Engineering Dept.

How to create a function:


To create a function that adds two numbers and strores the result in a third variable, type in it the
following code:
function add
x=3;
y=5;
z=x+y
Save the file by the name of add (in work folder, which is chosen by default), go back to the command
window and write
» add
z =
8

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).

Now go back to the editor/debugger and modify the program as follows


function adv(x,y)
%-------------------------------------------------
% This function takes two values as input,
% finds its sum, & displays the result.
% inputs: x & y
% output: z
% Example: addv(3,6)
% Result: z=9
%--------------------------------------------------
z=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.

 A script can have any name.


A function file is stored with the name specified after keyword function.

 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.

Relational and logical constructs

The relational operators in MATLAB are

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.

iii. If-elseif-end Construct: Another variation is


if <condition1>,
<program1>
elseif
<condition2>,
<program2>
end
Now if condition1 is not 0, then program1 is executed, if condition1 is 0 and if condition2 is not
0, then program2 is executed, and otherwise control is passed on to the next construction.
Looping constructs

i. For Loops : A for loop is a construction of the form


for i= 1 : n,
<program>,
end
The program will repeat <program> once for each index value i = 1, 2 .... n. Here are some examples of
MATLAB's for loop capabilities:

Example: The basic for loop


>> for i = 1 : 5,
c = 2*i
end
c =
2
..... lines of output removed ...
c=
10

computes and prints "c = 2*i" for i = 1, 2, ... 5.

Example: For looping constructs may be nested.


Here is an example of creating a matrices contents inside a nested for loop:
>> for i=1:10,
for j=1:10,
A(i,j) = i/j;
end
end
There are actually two loops here, with one nested inside the other; they define

14
Electrical & Computer Engineering Dept.

A(1,1), A(1,2), A(1,3) ... A(1,10), A(2,1), ... A(10,10)


in that order.

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.

Lab 3: Plotting of Continuous Time and Discrete Time Signals.


In this lab, we will focus on the use of MatLab Graphics. At the end of this lab the students will be
able to learn
• How to produce continuous time plots and how to modify them.
• How to create arrays of plots.
• How to create discrete time plots.
• How to plot a piece-wise signal.

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.

Plotting Discrete-Time Signals


In order to plot discrete time signals in MATLAB stem(n,x) command is used. Where n is always integer.
The following example illustrates the procedure:
>> n=-30:30;
>> x=sin(n/6);
>> stem (n,x)
We can also add label the x-axis, y-axis and give an appropriate title to our plots using the following
commands.
>> xlabel 'Samples'
>> ylabel 'x[n]'
>> title 'A Demo of Discrete signal display'
The complete code when executed provides us the following plot.

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]'

Continuous-Time Unit Step Function:

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.

MULTIPLE PLOTS ON SAME FIGURE WINDOW


Two ways to make multiple plots on a single graph are:
i. Single plot command
x = 0:0.01:2*pi;
y1=sin(x);
y2=sin(2*x);
y3 = sin(4*x);
plot(x,y1,x,y2,x,y3)
ii. Multiple plot commands
Another way is with hold. The command hold freezes the current graphics screen so that subsequent plots
are superimposed on it. Entering hold again releases the “hold”.
x = 0:0.01:2*pi;
y1=sin(x);
y2=sin(2*x);
y3 =sin(4*x);
plot(x,y1)
hold on
plot(x, y2)
plot(x,y3)
OVERRIDING THE DEFAULT PLOT SETTINGS
One can override the default line types and point types. For example, the command sequence
x = 0:0.01:2*pi;
y1=sin(x);
y2=sin(2*x);
y3=sin(4*x);
plot(x,y1,'--',x,y2,':',x,y3,'+')
grid
title ('Dashed line and dotted line graph')

19
Electrical & Computer Engineering Dept.

The line-type and mark-type are


Linetypes : solid (-), dashed (--). dotted (:), dashdot (-.), dashdash(--)
Marktypes : point (.), plus (+), star (*), circle (o), x-mark (x)

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

Plot the signal 𝑥(𝑡), against the variable 𝑡.


Hint: Use unit step function to generate unit impulse. For continuous unit step function you may use if else statement

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.

Lab 4: Transformation of Independent Variables

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

𝒙(𝒕 − 𝟒) = 𝒆−(𝒕−𝟒) 𝒖(𝒕 − 𝟒)


The function x(t-4) is plotted as

clear all
close all
clc

t=-10:0.1:10;%'t' should be generic and not changing for each code


x=heaviside(t).*exp(-t);%defining original signal x(t)
t0=2;%Shift data by t0>0 (R.H.S)
subplot(221),plot(t,x),title 'x(t)',xlabel 't',ylabel 'Amplitude'

x1=heaviside(t-t0).*exp(-(t-t0));%for shifting t we add -t0 to t


subplot(222),plot(t,x1),title(['x(t-(' num2str(t0) '))']),xlabel 't',ylabel
'Amplitude'

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'

% Above figure 4.7 (Oppenhiem 2nd Edition)


x3=heaviside(-t).*exp(t);%for flipping we replace t by -t
subplot(224),plot(t,x3),title 'x(-t)',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])

a=2;%Compression factor Figure 4.10 (Oppenhiem 2nd Edition)


x5=(heaviside(a*t+1)-heaviside(a*t)).*(a*t+1)+…
(heaviside(a*t)-heaviside(a*t-2))+…
(heaviside(a*t-2)-heaviside(a*t-3)).*(-a*t+3);
subplot(312),plot(t,x5)
title(['Signal by parts::x(' num2str(a) 't)'])
xlabel 't',ylabel 'Amplitude'
grid on, axis([-4 12 -1 1.5])

%Expansion by a Figure 4.10 (Oppenhiem 2nd Edition)


x6=(heaviside(t/a+1)-heaviside(t/a)).*(t/a
+1)+(heaviside(t/a)-heaviside(t/a-2))+(heaviside(t/a-2)-heaviside(t/a-3)).*(-
t/a+3);
subplot(313),plot(t,x6),title(['Signal by parts::x(t/' num2str(a)
')']),xlabel 't',ylabel 'Amplitude'

23
grid on, axis([-4 12 -1 1.5])

Tasks
Perform the given transformations on x(t) given as

(i) x(2t) + 1 (ii) x(4 – t/2)

24
Electrical & Computer Engineering Dept.

Lab 5: “Introduction to Matlab toolbox”

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

Creating Symbolic Variables and Expressions


The first step is to tell MATLAB that the variables to be used are symbolic. This is most easily done
using the syms command.
For example, in the following we will use a,b,c, x, fas symbolic variables
>>syms a b c x f;
We declared five symbolic variables.
Now let’s declare an equation
>> f = a*x^2+b*x+c;

Then we want to substitute numerical Values for a, b, c, x.

>>subs (f, {a,b,c,x}, {1,2,3,4})

ans = 27

For the details of subs command, read page 21 of the bookSymbolic MathToolbox.

We could also use the sym command.


The sym command lets you construct symbolic variables and expressions. Forexample, the
commands
x = sym('5')
a = sym('6')
create a symbolic variable x and substituted 5 for x and a symbolic variable a that has value 6.

Symbolic and Numeric Conversions


Read Page 21 of the book
Creating Symbolic Math Functions

25
Electrical & Computer Engineering Dept.

Read Page 28 of the book


Differentiation
To illustrate how to take derivatives using the Symbolic Math Toolbox, firstcreate a symbolic expression:
syms x
f = sin (5*x)
The command
diff (f)
differentiates f with respect to x:
ans =
5*cos(5*x)
Another example:
To find
df
diff_f =
dx
where f = 𝑒 −ax 𝑥 3𝑏 sin(cx) and a, b and c are unspecified constants, we do the following:
clear;
syms a b c x;
f=exp(-a*x)*x^(3*b)*sin(c*x);
diff_f = diff(f,x)
The result is:
diff_f =
(3*b*x^(3*b -1)*sin(c*x))/exp(a*x) +
(c*x^(3*b)*cos(c*x))/exp(a*x) - (a*x^(3*b)*sin(c*x))/exp(a*x)
Notice that the result is quite complex. To ask MATLAB to try to simplify it, type:
>>diff_f_simp = simple(diff_f)

Now the result is:


diff_f_simp =
(x^(3*b - 1)*(3*b*sin(c*x) + c*x*cos(c*x) -
a*x*sin(c*x)))/exp(a*x)

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.

Note: More details on Derivative page 30-35 of the book

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

Now try the following code:

value= limit(sin(x)/x,x,0)
value =
1

As we know from our calculus knowledge


 sin(ax)   sin( x) 
lim  a
& lim   1
x 0
 x 
x 0
 x 
Note: For details on Limits page 35-38 of the book

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)

When MATLAB is unable to find an analytical (symbolic) integral, such as with


>>int(exp(sin(x)),x,0,1)
a numerical solution can nevertheless be found using the “quad” command, e.g.
>>quad('exp(sin)',0,1)
Generally speaking, it is best to follow the steps below:

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

sums to π2 /6 , while the geometric series

sums to 1/(1-x) , provided that |x| < 1

Three summations are demonstrated below:

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).

We now look at some examples.

29
Electrical & Computer Engineering Dept.

Example:

Find the two solutions to the classic quadratic equation, ax2 + bx + c = 0.

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

double Convert symbolic matrix to MATLAB numeric form

int8, int16, int32, int64 Convert symbolic matrix to signed integers

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.

Lab 6: “Implementing Convolution Sum”

In this lab, we will implement the following operations:


Time Shift Convolution using vectors
Sum Convolution Sum in Matlab
Code for generating Input and Impulse Response

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]

Implementing Convolution Sum using Matlab built-in function


y=conv(h,x);
nf=(n(1)+n(1)):(n(1,length(n))+n(1,length(n)));
figure,stem(nf,y),title 'convolution using builtin function'
xlabel 'Samples--n',ylabel 'y[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]

Implementing Convolution Sum using user defined code


In order to make the coding a bit convenient we initially define a discrete unit step function using
sigmoid function.
function u=unit(n)
u=(sign(n+eps)+1)./2;
end

Now implementing signals, followed by convolution code in a step wise manner.

%Method 2
%Convolution Step by Step

33
Electrical & Computer Engineering Dept.

n=-50:50;

n0=n(1);%n0 is some negative quantity normally the initial value of 'n'


k=n; %replacing k by n
%%%Shift by n0
x=exp(-0.5*(k+n0)).*(unit(k+n0));

%%%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

h[n] & x[n-(50)]


1

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.

Lab 7: “Implementation of convolution integral”

In this lab, you will learn about the following topics:


Convolution Integral Finding Convolution Integral

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.

Finding Convolution Integral:


We will discuss two methods:
Method 1 (Numerical Method)
Step 1: Define/Sketch x (τ) and h (τ).
Step 2: The impulse response, h (τ) time-reversed or folded to obtain h (-τ).
Step 3: Then h (- τ) shifted by t to form h (t - τ) = h [-(τ - t)] which is a function of τ
with parameter t. Begin with shift t large and negative, i.e., shift h (- τ ) to the far left on the time
axis.
Step 4: The signal x (τ) and h (t - τ) are multiplied together for all values of τ with t fixed at some
value.
Step 5: The product x (τ) h (t- τ) is integrated over all τ to produce a single output value y (t).
Step 6: For Calculating the response of the system over all instants of time, repeat steps 3to 5 till
response at all time instants (t = -∞ to ∞) is obtained.

Method 2 (Symbolic Math Toolbox)


Step 1: Generate x ( τ) and h (t - τ). (Use syms)
Step 2: Multiply x ( τ) and h (t - τ).
Step 3: Find out limits of integration and use int to integrate product x ( τ) h (t- τ) with respect to
τ to produce output, y (t) (Recall pretty, simplify, collect and subs from the book that has been
uploaded on the portal).
Step 4: Use ezplot to sketch x(t), h(t) and y(t). Use subplot to show CT signals and
their convolution in single figure.
Let’s understand all this with the help of an example.

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.

Lab 8: “Implementation of Fourier Analysis and Fourier Synthesis”

Today’s Lab is about Continuous Time Fourier series i.e.


Fourier analysis Fourier synthesis

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

%Fourier Series Analysis


syms a0 ak k T T1 T2 t w y

T=4*T1;
w=2*pi/T;%omega

% calculate the DC comonent a0


a0=1/T0*int(1,t,-T1,T1);

%calculate the kth harmonic ak


ak=1/T*int(exp(-1i*k*w*t),t,-T1,T1);

N=10;%Number of +ive Coefficients

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

x(t) = a-1e-jw0t + a0 + a1ejw0t

x(t) = a-2e-j2w0t + a-1e-jw0t + a0 + a1ejw0t + a2ej2w0t


.
.

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

DC + first N=10 harmonics


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

DC + first + third harmonics N=20 Harmonics

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.

Help on these commands is available in MatLab help directory.

1. Open M-file or M-Book.


2. The first step is to generate a CTFT function. Thus, use the reserve word function and name
you are choosing for your code should also be the name of the M-file.
3. There should be two input arguments two the function t, x(t). While two output parameters Ω,
X(jΩ). Note: the length of Ω and t are distinguished and not interdependent.
4. Now two generate X(j Ω), we would be using vectors multiplications.
5. X(jΩ)= 𝑥(𝑡)𝑒 𝑗 Ω𝑡 𝑑𝑡; thus we require three vectors x, Ω and t.
6. Their transpose multiplication would generate the required CTFT.
7. 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.
8. Previously, generated unit step function would be quite a help in this Lab.

function [w,X]=CTFT(t,x)
w= -pi:0.01:pi;
ee=exp(-j*w'*t);
w=w./pi*1000;
X=x*ee';

The above function will calculate CTFT of any given signal.

Task: Generate a square wave and check out its transform.


Also view the frequency spectrum a triangular wave.
Generate a sinusoidal of Fn= Your Roll Number and Fs= 2000. And view its spectrum.

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.

Help on these commands is available in MatLab help directory.

9. Open M-file or M-Book.


10. The first step is to generate a DTFT function. Thus, use the reserve word function and name
you are choosing for your code should also be the name of the M-file.
11. There should be two input arguments two the function n, x[n]. While two output parameters
ω, X(𝑒 𝑗𝜔 ). Note: the length of ω and n are distinguished and not interdependent.
12. Now two generate X(𝑒 𝑗𝜔 ), we would be using vectors multiplications.
13. X(𝑒 𝑗𝜔 )=Σx[n] 𝑒 𝑗𝜔𝑛 ; thus, we require three vectors x, ω and n.
14. Their transpose multiplication would generate the required 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.

Lab 10: “Introduction to Speech Processing.”

Learning Objectives: At the end of this lab the students will be able to learn

How to read a speech signal in MATLAB.

How to play sound data.

How to reverse play sound data.

How to add echo in sound data.

How to apply simple digital filter on sound data.

How to fast play the sound data.

Time and frequency analysis of sound data.

What is digital sound data?

Getting some pre-recorded sound files (digital sound data)


You could download the following sounds from portal

Loading Sound files into MATLAB

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.

[guitar,fs]=wavread('gtr.wav'); % loads “gtr.wav” clip

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).

See the size of guitar: size(guitar)

Channels:

 Mono: There is one channel for example the guitar clip


 Stereo: There are two channels for example

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)');

ylabel('relative signal strength');

 
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!

fs = 48000; %48.0 khz

soundsc(left_guitar, fs) % plays left channel as monochannel

soundsc(right_guitar,fs) %plays right channel mono (soundsame)

soundsc(guitar,fs) % plays stereo

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.

Now let's try it on one of our sound arrays:

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=left_guitar; % set up a new array, same size as old one


N=10000; % delay amount N/44100 seconds for
n=N+1:length(left_guitar)

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

Digital Tone Control


The following program (or “digital filter”) is designed to soften high frequency components from the
signal (treble). It retains the low frequency components (bass). Applying this digital filter has the
same effect as turning down the treble tone control on your stereo. The design of this code is not so
obvious. The Electrical Engineering students will learn more about this type of frequency selective
digital filtering in ECE334 Discrete Signals and Systems.

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

soundsc(guitar,fs) % low pass filter

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

soundsc(out,fs) % high pass filtered

Changing the Speed

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...

soundsc(guitar,fs/1.5) % How slow can you go?


soundsc(guitar,fs*1.5)

Removing (Minimizing) Vocals

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?

Load some song

[song,fs]=wavread('song.wav'); % load some song clip


Left=song(:,1);
Left=song(:,2);

soundsc(left,fs); % Original left channel

soundsc(left-right,fs); % Long and winding road, virtually no vocal

Notice the voice is virtually eliminated…

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.

Time and Frequency Analysis:

Guitar:

function [ ] = guitar_analysis( )

% Load the clip

[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)');

ylabel('relative signal strength');

% Fourier Transform of voices

nfft = 2^nextpow2(length(guitar));

sound_spec = fft(guitar,nfft)/sqrt(nfft);

frange = fs/2 * linspace(0,1,nfft/2 + 1);

subplot(2,1,2);

plot(frange,2*abs(sound_spec(1:nfft/2+1)));

title('Frequency plot of guitar');

xlabel('frequecny(Hz)');

ylabel('Magnitude of fft');

%play the sound

wavplay(guitar,fs);

end

49
Electrical & Computer Engineering Dept.

function [ ] = frequency_analysis( )

clc;

clear all;

fs=48000;

figure(1);

% My voice of saying letter a

[a_gz, fs_gz] = wavread('a_gz.wav'); % contains 2 columns (stereo


channel), left channel and right channel

left_gz=a_gz(:,1);

%plot the left channel

time=(1/fs_gz)*length(left_gz);

t=linspace(0,time,length(left_gz));

subplot(3,1,1);

plot(t,left_gz);

title('My voice of saying a');

xlabel('time (sec)');

ylabel('relative signal strength');

% Basit's voice of saying letter a in lab


%plot the left channel

[a_basit, fs_basit] = wavread('a_basit.wav'); % basit's voice


left_basit=a_basit(:,1);
time=(1/fs_basit)*length(left_basit);
t=linspace(0,time,length(left_basit));

subplot(3,1,2);
plot(t,left_basit); title('Basit
voice of saying a'); xlabel('time
(sec)');

50
Electrical & Computer Engineering Dept.

ylabel('relative signal strength');

%Faryal's voice of saying letter a in lab


%plot the left channel

[a_faryal, fs_faryal] = wavread('a_faryal.wav'); % basit's voice

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);

title('Faryal voice of saying a');

xlabel('time (sec)');

ylabel('relative signal strength');

figure(2);

% Fourier Transform of voices

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);

frange_gz = fs_gz/2 * linspace(0,1,nfft_gz/2 + 1);

frange_basit = fs_basit/2 * linspace(0,1,nfft_basit/2 + 1);


frange_faryal = fs_faryal/2 * linspace(0,1,nfft_faryal/2 + 1);

51
Electrical & Computer Engineering Dept.

subplot(3,1,1);

plot(frange_gz,2*abs(sound_spec_gz(1:nfft_gz/2+1)));

title('Frequency plot (My voice of saying a)');

xlabel('frequecny(Hz)');

ylabel('Magnitude of fft');

subplot(3,1,2);

plot(frange_basit,2*abs(sound_spec_basit(1:nfft_basit/2+1)));

title('Frequency plot (Basit voice of saying a)');

xlabel('frequecny(Hz)');

ylabel('Magnitude of fft');

subplot(3,1,3);

plot(frange_faryal,2*abs(sound_spec_faryal(1:nfft_faryal/2+1)));

title('Frequency plot (Faryal voice of saying a)');

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.

Q.2. Convert your voice into opposite gender voice.

52
Electrical & Computer Engineering Dept.

Lab 11: “Introduction to Image Processing.”

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.

Purpose of Image Processing

The purpose of image processing is divided into 5 groups. They are:


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.

Fundamental steps of Image Processing.

Following are the steps for fundamental image processing in Matlab:

Loading and Displaying Image in MATLAB

In order to read the image we use the following command in MATLAB

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);

The image will open in a new window.

Example:

InputImg = imread('sample.jpg');

imshow(InputImg)

RGB Components of an Image

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:

redimage = InputImg; % Create a new matrix equal to the matrix %


of your original image.

redimage (:, :, 2:3) = 0; % This selectively nullifies the second

% and third columns of the colormap


% matrix which are part of the original matrix.

54
Electrical & Computer Engineering Dept.

% Since the colors are mapped using RGB, or columns


with values of Red, Green and Blue, so we can selectively nullify the green and blue columns to obtain
only the red part of the image.

imshow(redimage); % show the redimage that you just created.

Similarly, we can do the same with the green and blue components of the image. Just keep in mind the
format of the array

Red : Green : Blue

1 2 3

Conversion from RGB to Gray Scale


RGB image is three channel image conversion of 3-channel into one channel gives a gray scale image.

Code
InputImg = Imread('sample.jpg');

figure

Imshow(InputImg) % RGB Image

GImg = InputImg(:,:,1)

figure

imshow(GImg) % Gray Scale image


InputImgGray =rgb2gray(InputImg); % Using MATLAB built-in function

figure

imshow(InputImgGray)

55
Electrical & Computer Engineering Dept.

Conversion from Gray Scale to Binary Image.

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

Imshow(inputImg) % RGB Image

GImg = inputImg(:,:,1);

figure

imshow(GImg) % Gray Scale image


[Height Width]=size(GImg(:,:,1));

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

Imshow(BinaryImg) % Binary Image

56
Electrical & Computer Engineering Dept.

Lab Tasks

Q.1. Load given image and convert it into binary image. Display original image and binary
image.

Q.2. Detect triangle from the given image.

57
Electrical & Computer Engineering Dept.

Signals and Systems Lab


CLOs
Lab Type Experiment No. and Name
CLO-1 CLO-2 CLO-3
√ (100%)
1. Introduction to MATLAB.
2. Introduction to Script and √ (100%)
Function Files, Loops and
Conditional Statements.
3. Plotting of Continuous Time √ (100%)
and Discrete Time Signals.
4. Transformation of Independent √ (100%)
Variables.
√ (10%) √ (70%) √ (20%)
Lab Sessional-I.
Typical 5. Introduction to Symbolic Math √ (100%)
Toolbox.
6. Implementation of Convolution √ (100%)
Sum.
7. Implementation of Convolution √ (100%)
Integral.
8. Implementation of Fourier √ (100%)
Series.
9. Implementation of Fourier √ (100%)
Transform.
√ (10%) √ (70%) √ (20%)
Lab Sessional-II.
√ (100%)
10. Open Ended-1: Introduction to
Speech Processing.
Open Ended 11. Open Ended-2: Introduction to √ (100%)
Two Dimensional Signals
(Image Processing.)
Open Ended Lab Final/Project √ (10%) √ (70%) √ (20%)

58

You might also like