Вы находитесь на странице: 1из 82

Lab Manual

Signals and Systems


(EE 2511)

Revised By:
Faraz Hasan Khan

Revised On:
1st August, 2016

Department of Electrical Engineering


The University of Lahore, Lahore, Pakistan
1-KM Raiwind Road, Lahore.

1
Revision History

Revised Date Revised By Revised Topics


August 1,2016 Faraz Hasan Khan 1. The manual has been updated
according to HEC guidelines.
Lab # 14 & 15 which were
previously about Image Processing
are now replaced with sampling,
quantization and reconstruction of
band limited signals using
MATLAB.
September 5,2015 Saad Afzal 2. Fisrt two labs on MATLAB
introduction were revised.

January 10,2010 Abdul Rehman Yasin 3. Labs on signal addition and


multiplication were revised. Details
in Fourier Transform were added.

2
CERTIFICATE OF APPROVAL

It is certified that the lab manual titled “Signals and Systems”, in scope and in quality, covers the
objectives and topics defined in the course outline.

Remarks by Mentor: -------------------------------------------------


Dr. Ishtiaq Ahmad
Assistant Professor
Department of Electrical Engineering
The University of Lahore

Remarks by HOD: -------------------------------------------------


Hafiz Tehzib ul Hassan
Associate Professor
Department of Electrical Engineering
The University of Lahore

3
Table of contents

Lab 01: Introduction to MATLAB ………………………………………7

Lab 02: Introduction to MATLAB (CONT’D)…………………………11

Lab 03: Introduction to Vectors and Matrices ……………………..…..16

Lab 04: Implementation of Basic Sequences and Energy of a Signal…20

Lab 05: Generation of Exponential and Random Signals…………….27

Lab 06: Implementation of Addition and Multiplication of Signals….30

Lab 07: Implementation of Shifting, Folding and Scaling of Signals…33

Lab 08: Discrete and Continuous Time Convolution………………......37

Lab 09: Harmonic Sequences in MATLAB……………………………..43

Lab 10: Fourier Series Magnitude and Phase Calculation …………….49

Lab 11: Continuous Time Fourier Transform………………………….54

Lab 12: Discrete Time Fourier Transform……………………..……..…58

Lab 13: Properties of Fourier Transform………………………………..63

Lab 14 & 15: Sampling, Quantization and Reconstruction of Signals..…68

Lab 16: Generation of Different Signals…………………………..….…78

4
Signal and System Labs
Preface

This course deals with signals, systems, and transforms, from their theoretical mathematical foundations
to practical implementation in circuits and computer algorithms.
Whether analog or digital, information is represented by the fundamental quantity in electrical
engineering: the signal. Stated in mathematical terms, a signal is merely a function. Representation of
signals by sample values; discrete-time filter characterization and response; the z-transform; continuous-
time signals and linear, time-invariant systems; frequency response; continuous-time Fourier transform
and application to system analysis. MATLAB basics with application to signals and systems.
The manual presents and integrates the basic concepts for both continuous-time and discrete-time signals
and systems. Signal and system representations are developed for both time and frequency domains.
These representations are related through the Fourier transform and its generalizations, which are
explored in detail. Filtering and filter design, modulation, and sampling for both analog and digital
systems.
MATLAB is an environment for performing calculations and simulations of a variety of types.
MATLAB, short for matrix laboratory, was developed by Cleve Moler, a professor of mathematics and
computer science, in the late 70s and early 80s. In 1984, Cleve Moler and Jack Little founded The Math
Works which has been developing MATLAB ever since. In the earliest version of MATLAB, there were
about 80 commands, and they allowed for matrix calculations. Now there are thousands of commands,
and there are many, many types of calculations that one can perform. Simulink is a MATLAB “add-on”
that allows one to simulate systems by combining blocks of various types. We will make use of Simulink
as well. During the course of this lab, the student will learn how to make calculations using MATLAB
and will learn a little about simulating systems using the simulation tools provided by MATLAB and
Simulink.

Why Use MATLAB?

There are several goals for the development of a suite of effective demonstrations and applications for
teaching MSP. First, the concepts must be presented clearly with little interfering information. Second the
applications should be direct, flexible, and fast. Third, both sound and image must be used to demonstrate
concepts. Fourth, the demonstrations should leave plenty to explore. Fifth, a student should be able to
look into the code to understand how it works. Sixth, the demonstrations should be compatible with as
many computer platforms possible. And finally, the cost to students to be able to run the applications on
their own computer should be minimal.

There are a several low-level programming languages that can be used to demonstrate the application of
DSP, such as C++, and Java. But these require a high proficiency in programming, not to mention the
tangle of cross-platform issues. Sound processing languages Super Collider (McCartney 1996) or the
graphical programming applications Max/MSP or pd (Puckette 1996), can also be used to create
interesting demonstrations, but only for sound. Though these have excellent real-time capability, they
have marginal abilities for visual data display.

5
There are several high-level software packages that can be used to teach signal processing, such as
Mathematica, Octave, and MATLAB. A good overview of these and other packages in terms of
engineering education can be found in (Nagrial 2002). Mathematica is meant more for symbolic
mathematics than creating applications and it cannot easily produce sound. Octave, a free open-source
mathematics software application, is quite compatible with MATLAB code, but it lacks much of the rich
library of functions in MATLAB. In addition there is no easy way to create graphical user interfaces
(GUIs).

MATLAB provides a flexible integrated programming environment that is easy to use and understand,
and cheap for students. MATLAB is platform independent, has superior graphics handling and
visualization capabilities, and has a great GUI development environment for wrapping applications. In
addition it offers unparalleled functionality with many different data formats. It has an extensive library of
routines, and “toolboxes” can be purchased to add more specialized functionality, such as advanced signal
and image processing routines. Applications written in MATLAB are open; any user can look at the code.
Furthermore, countless institutions, both academic and corporate, as well as many independent users
worldwide, use MATLAB for algorithm development, quick prototyping, and complex problem solving.
A drawback to using MATLAB, however, is its lack of real-time functions, like tracking a sound as it
plays, or visualizing a spectrogram straight from the sound input. Though there should be some
familiarity with vectors and matrices, the MATLAB programming language is easy to learn and intuitive.
For these reasons it is clear that MATLAB is the best choice for developing applications that satisfy the
several criteria above.

6
Lab # 1
Introduction to MATLAB
Name: Registration #
Section:

Objective

The objective of this lab is to introduce students to the Matlab environment and enable them to perform
basic mathematical operations.

1. Introduction

The MATLAB® high-performance language for technical computing integrates computation,


visualization, and programming in an easy-to-use environment where problems and solutions are
expressed in familiar mathematical notation.
MATLAB is an interactive system which allows you to solve many technical computing problems. The
name MATLAB stands for matrix laboratory. MATLAB was originally written to provide easy access to
matrix software developed by the LINPACK and EISPACK projects. Today, MATLAB engines
incorporate the LAPACK and BLAS libraries, embedding the state of the art in software for matrix
computation.

2. The MATLAB System

The MATLAB system consists of these main parts:

2.1 Desktop Tools and Development Environment

This part of MATLAB is the set of tools and facilities that help you use and become more productive with
MATLAB functions and files. Many of these tools are graphical user interfaces. It includes: the
MATLAB desktop and Command Window, an editor and debugger, a code analyzer, and browsers for
viewing help, the workspace, and folders.

2.2 Mathematical Function Library

This library is a vast collection of computational algorithms ranging from elementary functions, like sum,
sine, cosine, and complex arithmetic, to more sophisticated functions like matrix inverse, matrix Eigen
values, Bessel functions, and fast Fourier transforms.

2.3 The Language

The MATLAB language is a high-level matrix/array language with control flow statements, functions,
data structures, input/output, and object-oriented programming features. It allows both “programming in
the small” to rapidly create quick programs you do not intend to reuse. You can also do “programming in
the large” to create complex application programs intended for reuse.

7
2.4 Graphics

MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as annotating and
printing these graphs. It includes high-level functions for two-dimensional and three-dimensional data
visualization, image processing, animation, and presentation graphics. It also includes low-level functions
that allow you to fully customize the appearance of graphics as well as to build complete graphical user
interfaces on your MATLAB applications.

2.5 External Interfaces

The external interfaces library allows you to write C and Fortran programs that interact with MATLAB. It
includes facilities for calling routines from MATLAB (dynamic linking), for calling MATLAB as a
computational engine, and for reading and writing MAT-files.

3. The MATLAB interface

Current Directory – Workspace –


Command Window – where your programs where variables
here commands are or M-files are saved are displayed
entered

Name -- Your folders and


Command History –
files in the current
your commands which
directory
you have entered in
near past
8
4. Basic operations in MATLAB

Operators

Expressions use familiar arithmetic operators and precedence rules.


+ Addition
- Subtraction
* Multiplication
/ Division
^ Power
' Complex conjugate transpose
.* Element-by-element multiplication
./ Element-by-element division
.^ Element-by-element power

---------------------------------------------------------------------------------------------------------------------

Examples:
If a = 23, b = 9
Find a + b.
>> a= 23
>>b=9
>> a+b
Write your output:

Learning Outcomes

Introduction of Matlab and its basic mathematical operations.

Questions

Exercise # 1: Evaluate a-b, a*b, a/b and a ^ b. Write all commands and outputs in your note
books.
Exercise # 2: Evaluate a.*b, a. /b, a. ^b. Write all commands and outputs in your note books.
Exercise # 3: Find out the difference between a*b and a.*b.

9
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory 2 = Fair 3= Satisfactory 4 = Very good 5= Excellent

Questions Rating Remarks


(1 to 5)

1. To what extent did you learn on the material in the


lab?

2. Are you able to apply knowledge gained in the lab to


similar problems?

3. Are you able to analyze and interpret data recorded


in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design a system, component or process to


fulfill certain specifications based on the knowledge
acquired in the lab?

6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?

8. Comment whether your work in the lab has an


impact on the society.

Additional Comments (if any):


---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------

10
Lab # 2
Introduction to MATLAB
(cont'd)
Name: Registration #
Section:

Objective

Introduction to Variables and Arrays in MATLAB.

Introduction

The functional unit of data in any Matlab program is array. An Array is a collection of data values
organized into rows and columns and known by a single name.

Arrays can be classified as either vectors or matrices. The term VECTOR is usually used to describe an
array with only one dimension. While the term MATRIX is usually used to describe an array with two or
more dimensions. Following section will explain how we can declare any vector or signal in MATLAB.
Size of array is specified by the number of rows and the number of columns in the array, with the number
of rows mentioned first. The total number of elements in the array will be the product of the number of
rows and the number of columns.

Try using these values:

[3.4]
[1.0 2.0 3.0]
[1.0; 2.0; 3.0]
[1, 2, 3; 4, 5, 6]
[1, 2, 3, 4, 5, 6]
[]

Not all the elements of an array need to be defined when it is created. If a specific array element is
defined and one or more of the elements before it are not, then the earlier elements are automatically
created and initialized to zero. For example, if c is not previously defined, the statement

C(2,3)=5
Will produce matrix 0 0 0
005

Similarly the array d=[1 2]. Then the statement

d(4)=4

will produce d=[1 2 0 4].


Initializing with shortcut expressions

11
Matlab provides a special shortcut notation for these circumstances using the COLON operator. The
colon operator specifies a whole series of values by specifying the first vales in the series, the stepping
increment and then the last value in the series. The general form of a colon operator is
First: increment: last

For example
x=1:2:10
will generate x= 1 3 5 7 9
Try using angles=(0.01:0.01:1.00)*pi;

Transpose Operator(‘)

This operator swaps the rows and columns of any array that it is applied to.
For example try using:
F=[1:4]
And F=[1:4]’

Initializing with Built-in Functions

Try using these:


A=zeros(2)
B=zeros(2,3)
C=[1 2; 3 4]
D=zeros(size(C))
E=ones(3)
E=ones(3,1)
E=eye(3)
E=eye(3,2)
Length(C).//Generate the longest dimension of the array.

Zeros can be used to create an all zero array of any desired size. If function has a single square array; it
will generate a square array using the single argument as both the number of rows and columns. size
function returns two values containing the number of rows and columns in an array.

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

Multidimensioanl Array
Matlab allows us to create arrays as many dimensions as necessary for any given problem. These arrays
have one subscript for each dimension and an individual element in the array will be the product of the
maximum value of each subscript. For example the following two statements create a 2X2X3 array C:

C(:,:,1)=[1 2 3; 4 5 6];
C(:,:,2)=[7 8 9; 10 11 12];
Whos C

12
Sub Arrays
It is possible to select and use subsets of arrays as though they were separate arrays. To select a portion
of array, just include a list of all of the elements to be selected in the parenthesis after the rray name. For
example:
Arr1=[1.1 2.2 3.3 4.4 5.5]
Try using Arr1(3)
And Arr1([1 4])
And also Arr1(1:2:5)

End Function
It is very useful for creating array subscripts. When used in an array subscript; end returns the highest
value taken on by that subscript. For example. Suppose that array Arr3 is defined as follows:

Arr3=[ 1 2 3 4 5 6 7 8];

Then Arr3(5:end) would be the array [5 6 7 8] and Arr3(end) would generate 8.


The value returned by end is always the highest value of a given subscript. Is end appears in different
subscripts, it can return different values within the same expression. For example, suppose that the 3X4
array Arr4 is defined as follows:

Arr4=[1 2 3 4; 5 6 7 8; 9 10 11 12];

Then the expression


Arr4(2:end, 2:end)

would return the array.(Try this one).

Note: Do all exercises using script files.

Learning Outcomes

Students will be able to understand the use of Variables and Arrays in MATLAB.

Questions

Exercise # 1: Find out the following matrices.

(a) Generate a 6X6 Matrix


(b) Generate a 6X1 Matrix
(c) Generate a 3X4 Matrix

Exercise # 2: Answer the following questions for the array shown below.

1.1 0.0 2.1 -3.5 6.0


0.0 1.1 -6.6 2.8 3.4
1.1 0.1 0.3 -0.4 1.3
-1.4 5.1 0.0 1.1 0.0

(a) What is the size of the array?

13
(b) What is the value of the array(4,1)?
(c) What is the size and value of array( : , 1 : 2 )?
(d) What is the size and Value of the (array[1 3],end)?

Exercise # 3: Assume the above matrix and find out the followings.

(a) array(3,:)
(b) array(:,3)
(c) array(1:2:3,[3 3 4])
(d) array([1 1],:)

Exercise # 4 Determine the size and contents of the follwings arrays. Note that the later arrays may
depend on the definition of arrays defined earlier in this exercise.
(a) a=1:2:5
(b) b=[a’ a’ a’]
(c) c=b(1:2:3,1:2:3);
(d) d=a+b(2,:);
(e) w=[zeros(1,3) ones(3,1)’ 3:5’]
(f) b([1 3],2 )=b([3 1],2);

14
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory 2 = Fair 3= Satisfactory 4 = Very good 5= Excellent

Questions Rating Remarks


(1 to 5)

1. To what extent did you learn on the material in the


lab?

2. Are you able to apply knowledge gained in the lab to


similar problems?

3. Are you able to analyze and interpret data recorded


in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design a system, component or process to


fulfill certain specifications based on the knowledge
acquired in the lab?

6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?

8. Comment whether your work in the lab has an


impact on the society.

Additional Comments (if any):


---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------

15
Lab # 3
Introduction to Vectors and Matrices

Name: Registration #
Section:

Objective

Introduction to Vectors in MATLAB

Introduction

Following section will explain how we can declare any vector or signal in MATLAB.

 Simple Scalar

Scalars are numbers such as 1, 6, 9, 0 etc. To enter scalars in MATLAB the command will be
>>a = 4

 Row Vector:

Row vectors are those which have only one row such as [1, 2, 3, 8, 7]. To enter row vector in MATLAB
the command will be
>>a = [1, 2, 3, 8, 7] OR
>> a= [1 2 3 8 7]

 Column Vector:

1
Column vectors are those which have only one column such as 2 . To enter Column vector in
8
MATLAB the command will be

>>b = [1; 2; 8]

Matrix

Following section will explain how we can declare matrix in MATLAB.

1 2 3
To enter matrix X= 4 5 6 in MATLAB the command will be
7 8 9

16
Note: If you want to multiple two signals then we have to use the .* operator. It will perform index by
index multiplication.

Basic Operations On Vectors:

Example 1: a = [1 2 3]
b = [5 6 7]
Find
c= a+b, d= a-b , v= a*b ,w= a .*b, x= a./b

Write the output of each command in your note book and explain the difference between a*b and a.*b.

Getting help

To view the online documentation, select MATLAB Help from Help menu or MATLAB Help directly in
the Command Window. The preferred method is to use the Help Browser. The Help Browser can be
started by selecting the ? Icon from the desktop toolbar. On the other hand, information about any
command is available by typing
>> help <Command> or
>> doc <Command>

Plot a function

The MATLAB environment provides a wide variety of techniques to display data graphically. Interactive
tools enable you to manipulate graphs to achieve results that reveal the most information about your data.
We can plot any function using MATLAB commands plot/ stem. Stem will create a discrete function.
While plot will generate a continuous function.

Example # 2: Compute and plot the sample values of a 0.5 Hz cos wave. Samples are taken every 0.1 sec
and the time interval of the signal is from 0 to 10sec.
---------------------------------------------------------------------------------------------------------------------
>>n = 0:0.1:10
>> y = cos(2*pi*0.5*n) %here w=2πf So f=0.5Hz.
>> hold on
>> plot (n,y)
>> stem (n,y)
>> xlabel('X Axis')
>> ylabel('Plot Y Axis')
>> title ('Cos function with f= 0.5Hz')
>> hold off
>> grid
Note: % is used for comments.

Use help command to find out how we can plot two plots in different colors and with different line
format.

17
Write comments in your note book.

Executable Files:

The MATLAB software provides a full programming language that enables you to write a series of
MATLAB statements into a file and then execute them with a single command. MATLAB allows you to
perform more complex operations and it is easier to repeat these operations. For this purpose you will
need to create the file. The easiest way is to use the built in MATLAB editor. It will allow you to do some
very simple manipulations. When you write a MATLAB function or script, you save it to a file called an
M-file .

Types of M-files:
There are two types of M-files that you can write:

Scripts:
 These are useful for automating a series of steps you need to perform many times.
 They do not accept input arguments and return output arguments.
 They store variables in a workspace internal to the function.

Functions:
 They are useful for extending the MATLAB language for your application.
 They can accept input arguments and return output arguments.
 They store variables in a workspace internal to the function.

To get MATLAB to execute the commands in the file simply type in the name of the file with which you
saved it. MATLAB will then search the current directory for the file and then it will read the file and
execute the commands in the file. MATLAB will show an error if you will type wrong file name.

Note: Do all exercises using script files.

Learning Outcomes

Use of vectors and how to plot graphs in MATLAB.

Questions

Exercise # 1: This M-file calculates and plot the function sin(x) for 0<=x<=6
X=0:0.1:6;
Y=sin(X);
plot(X,Y);
Exercise # 2: Modify Example 2 Use different sampling interval and observe the behavior.
Exercise # 3: Modify Example 2 code such that continuous wave form is dotted and in green color also
use subplot instead of hold.
Exercise # 4: Compute and plot the sample values of a 0.3 Hz sin wave. Samples are taken every 0.5 sec
and the time interval of the signal is from 0 to 10 sec.

18
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory 2 = Fair 3= Satisfactory 4 = Very good 5= Excellent

Questions Rating Remarks


(1 to 5)

1. To what extent did you learn on the material in the


lab?

2. Are you able to apply knowledge gained in the lab to


similar problems?

3. Are you able to analyze and interpret data recorded


in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design a system, component or process to


fulfill certain specifications based on the knowledge
acquired in the lab?

6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?

8. Comment whether your work in the lab has an


impact on the society.

Additional Comments (if any):


---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------

19
Lab # 4
Implementation of basic sequences and Energy of a signal

Name: Registration #
Section:

Objective

This lab is designed to implemented impulse (sample) function in MATLAB. Students will also learn
how to flip & Shift Signals and how to plot Unit impulse. They will also learn how to compute power of a
signal

Introduction

Signals are represented mathematically as functions of one or more independent variables. For
convenience, we generally refer to the independent variable as time. Signals are broadly classified into
analog and discrete signals.
An analog signal will be denoted by 𝑥𝑎 (𝑡) in which the variable 𝑡 represents time in seconds.
A discrete signal will be denoted by 𝑥(𝑛) in which the variable 𝑛 is integer and represents discrete
instances in time. It is also represented as
𝑥(𝑛) = {𝑥(𝑛)} = {… . , 𝑥(−1), 𝑥(0), 𝑥(1), … } (1)

Where the up-arrow indicates the sample at n=0. In MATLAB we can represent a finite–duration
sequence by a row vector of appropriate values. However, such a vector doesn’t have any information
about sample position n. Therefore a correct representation of 𝑥(𝑛) would require two vectors, one each
for "𝑥" and "𝑛" .

Unit Impulse Sequence:

Informally, impulse function is a function representing an infinitely sharp peak bounding unit area: a
function δ(x) has the value zero everywhere except at x = 0 where its value is infinitely large in such a
way that its total integral is 1. In the context of signal processing it is often referred to as the unit impulse
function.

20
1 𝑛=0
𝛿(𝑛) = {
0 𝑛≠0

Write the following function in the M-file or script file.

function[x, n] =impseq (n0, n1, n2)


% Generates x[n] =delta (n-n0) ; n1<=n<=n2
% n1 is lower limit of required sequence; n2 is upper limit of required
sequence
n=n1:n2;
x=(n-n0)==0;
stem(n,x);
title('Unit Impulse');
xlabel('n');
ylabel('x');

Now save the file with the name of impseq.m. You always have to save the functions with the exact
function name. In command window give the command
>> impseq(0,0,30)

Draw the plot in your note book.

Code to flip a signal:

--------------------------------------------------------------------------------------------------------------------------------------------

n = [1,2,3,4,5];
x = [-1,2,4,6,8];
subplot(2,1,1);
stem(n,x);
subplot(2,1,2);
y = fliplr(x);
n = -fliplr(n);
stem(n,y);

21
Graph:

Shift of the original signal :

--------------------------------------------------------------------------------------------------------------------------------------------
n = [1,2,3,4,5,6,7,8,9,10];
x = [5,2,4,6,8,10,8,6,4,5];
subplot(2,1,1);
stem(n,x);
n = n+5;
subplot(2,1,2);
stem(n,x);
--------------------------------------------------------------------------------------------------------------------------------------------

Power in the signal:

Consider the following discrete periodic and non-periodic signals in following Figure. For the periodic
signal find the period N and also the average power. For the non-periodic signals, find the total energy.

Solution:
For the first discrete signal in Figure, the signal x(n) is periodic with period N = 3. The average power is
then:

1 1 1 1 1 1 5
P(n) = N ∑N−1
N=0|x(n)|
2
= N3
∑2N=0|x(n)|2 =
3
( 12 + ( 2 )2 + 02 ) = 3
(1+ 4 ) = 12

22
Figure compute the power in the signal

We can use Matlab script to compute the power of the above signal as follow:
--------------------------------------------------------------------------------------------------------------------------------------------

%calculating average power for x(n)


%The signal
x = [1 0.5 0];
N = 3; % the period
% implementing the equation for power
pp = sum(abs(x).^2);
p = pp/N; % the average power

--------------------------------------------------------------------------------------------------------------------------------------------

Learning Outcomes

Implementation of basic sequences such as unit step and impulse, to find out energy of a signal
in Matlab.

Questions

Exercise 1: Plot the following function in your note book.


1 𝑛 = 15
𝛿(𝑛) = {
0 𝑛 ≠ 15

Unit step sequence:

1 𝑛≥0
𝜇(𝑛) = {
0 𝑛<0

23
function [x,n] = stepseq(n0,n1,n2)
% Generates x(n) = n(n-n0); n1 <= n <= n2
% ------------------------------------------
% [x,n] = stepseq(n0,nl,n2)
n = n1 :n2;
x = [(n-n0) >= 0];
stem(n,x);
title('Step Sequence');
xlabel('n');
ylabel('μ[n]');

What will the command to run the above code? Draw the plot in your note books.

Exercise 2: Plot the following function in your note book .


1 𝑛 ≥ 15
𝜇(𝑛) = {
0 𝑛 < 15

Signal energy:
The energy of a sequence 𝑥(𝑛) is given by

𝐸𝑥 = ∑ |𝑥(𝑛)|2
𝑛= −∞
Exercise 3: Write a command to find out the power of the following signal
𝑥(𝑛) = { 1, 2, 3, 4, 5, 5, 6, 7} −3 ≤ 𝑛 ≤ 4
Hint: Use sum and abs functions.

Exercise 4: Write a function flir_r(n,x) that takes a signal as input and returns its flipped version.

24
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory 2 = Fair 3= Satisfactory 4 = Very good 5= Excellent

Questions Rating Remarks


(1 to 5)

1. To what extent did you learn on the material in the


lab?

2. Are you able to apply knowledge gained in the lab to


similar problems?

3. Are you able to analyze and interpret data recorded


in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design a system, component or process to


fulfill certain specifications based on the knowledge
acquired in the lab?

6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?

8. Comment whether your work in the lab has an


impact on the society.

Additional Comments (if any):


---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------.

25
Lab # 5
Generation of exponential and random signals in MATLAB

Name: Registration #
Section:

Objective

Learn how to generate exponential and random signals in MATLAB.

Introduction

Types of Exponential function

There are three types of exponential functions i.e. Real exponentials complex exponential and imaginary
exponential. Following section will discuss all of them with examples.

Real Exponential Sequence


𝑥[𝑛] = 𝑎𝑛

In MATLAB, we can write


a = input (‘Type in argument =’);
K = input (‘Type in the gain constant = ’);
N = input (‘Type in length of sequence = ’);
n = 0: N ;
x = k * a .^n;
stem (n,x );
xlabel (‘Time index n’);
ylabel (‘Amplitude’);

use N=10, K=1, a=1


Use different values of K and a to observe behavior.

Complex-valued Exponential Sequence:

𝑥[n] = e(a+jω0 )n ∀ 𝑛

a = input (‘Type in real exponent =’);


b = input (‘Type in imaginary exponent =’);
c = a + b* i;
K = input (‘Type in the gain constant = ’);

26
N = input (‘Type in length of sequence = ’);
n = 1 : N;
x = K *exp (c*n);
stem (n,real(x));
xlabel ( ‘Time index n’);
ylabel(‘Amplitude’);
title (‘Real Part’);
disp ( ‘Press Return for imaginary part’);
pause
stem ( n,imag(x));
xlabel ( ‘Time index n’);
ylabel (‘Amplitude’);
title (‘Imaginary Part’);

Sinusoidal Sequence:

Imaginary powered exponential functions generate sinusoidal waveforms. Generally they can be
represented as;

𝑥[𝑛] = cos(𝜔0 𝑛 + 𝜃 ) ∀𝑛

The following exercise will explain it. MATLAB function 𝑠𝑖𝑛 or 𝑐𝑜𝑠 is used to generatte sinusoid
sequences.
Random Sequences

Many practical signals can’t be described by mathematical expressions like those explained above. Such
sequences are called the random (or stochastic) sequences and characterized by probability density
function or statistical moments.
In MATLAB we use the following command to generate random function.
>>rand(0,1)
It returns a pseudorandom scalar drawn from the standard uniform distribution on the open interval (0,1).

Learning Outcomes

How to generate exponential and random signals in Matlab

Questions

Exercise 1 : Write a command to plot an increasing exponential .Draw the plot in your note books.
Exercise 2: Write a command to plot x[n]= e^(2 + j3)n -10≤n≤10 . Draw the plot in your note books.
𝜋
Exercise 3: Generate a script file to plot 𝑥[𝑛] = 𝑐𝑜𝑠 (0.5𝜋𝑛 + 3 ) + sin(0.5𝜋𝑛) −50 ≤ 𝑛 ≤ 50 .
Exercise 4: Generate a script file to plot 𝑥[𝑛] = 𝑟𝑎𝑛𝑑(1,101) − 50 ≤ 𝑛 ≤ 50
Exercise 5: Generate a script file to plot 𝑥[𝑛] = 𝑠𝑖𝑛(𝑛)𝑒 (−4𝜋𝑛) , 0 ≤ 𝑛 ≤ 10.

27
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory 2 = Fair 3= Satisfactory 4 = Very good 5= Excellent

Questions Rating Remarks


(1 to 5)

1. To what extent did you learn on the material in the


lab?

2. Are you able to apply knowledge gained in the lab to


similar problems?

3. Are you able to analyze and interpret data recorded


in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design a system, component or process to


fulfill certain specifications based on the knowledge
acquired in the lab?

6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?

8. Comment whether your work in the lab has an


impact on the society.

Additional Comments (if any):


---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------

28
Lab # 6
Implementation of addition and multiplication of signals

Name: Registration #
Section:

Objective

Addition and multiplication of signals with different sampling times in Matlab

Introduction

Signal addition: This is a sample-by-sample addition given by


{𝑥1 (𝑛)} + { 𝑥2 (𝑛)} = { 𝑥1 (𝑛) + 𝑥2 (𝑛)}
It is implemented in MATLAB by the arithmetic operator "+". However, the lengths of 𝑥1 (𝑛) and 𝑥2 (𝑛)
must be the same. If sequences are of unequal lengths, or if the sample positions are different for equal-
length sequences, then we cannot directly use the operator +. We have to first augment 𝑥1 (𝑛) and 𝑥2 (𝑛)
so that they have the same position vector n (and hence the same length). This requires careful attention to
MATLAB's indexing operations. In particular, logical operation of intersection "&", relational operations
like "<=" and "=" are required to make (𝑛) and 𝑥2 (𝑛) of equal length. The following function, called the
sigadd function, demonstrates these operations.
Consider the sequence x1=[1,2,3,4], which was sampled at sample time indices n1 = [-1,0,1,2], which we
would like to add to sequence x2=[4,3,2,1], which was sampled at time indices n2 = [2,3,4,5]. To make
these two sequences equal in length, we’ll prepend and postpend zeros as needed to result in two
sequences of equal length that retain the proper time alignment. We see that the minimum time index is -1
and the maximum time index is 5. Since x1 starts at the minimum time index, we postpend zeros to it
such that we would have x1 = [1,2,3,4,0,0,0], with corresponding time indices [-1,0,1,2,3,4,5]. Similarly,
we prepend zeros so that x2 = [0,0,0,4,3,2,1], with the same total time or sample index range as the
modified version of x1.
The sum is then
x1 + x2 = [1,2,3,4,0,0,0] + [0,0,0,4,3,2,1] = [1,2,3,8,3,2,1]
and has time indices [-1,0,1,2,3,4,5].
These two ideas, that sequences to be added or multiplied must be of equal length, but also properly time-
aligned, lead us to write several MathScript functions that will automatically perform the needed
adjustments and perform the arithmetic operation.
The following script will perform addition of offset sequences y1 and y2 that have respective time indices
n1 and n2 using the method of prepending and postpending zero.

function [y,n] = sigadd(x1,n1,x2,n2)


%implements y (n) = x1(n) +x2 (n)
%-----------------------------
% [y,n] & sigadd(x1,n1,x2,n2)
% y = sum sequence over n, which includes n1 and n2

29
% x1 = first sequence over n1
% x2 = second sequence over n2 (n2 can be different from n1)
n = min(min(n1),min(n2)):max(max(n1),max(n2)); % duration of y(n)
y1 = zeros(1,length(n));
y2 = y1; % initialization
y1((n>=min(n1))&(n<=max(n1)))=x1;% x1 with duration of y
y2((n>=min(n2))&(n<=max(n2)))=x2; % x2 with duration of y
y = y1+y2; % sequence addition

Signal multiplication: This is a sample-by-sample multiplication (or "dot" multiplication) given by


{𝑥1 (𝑛)} . {𝑥2 (𝑛)} = {𝑥1 (𝑛)𝑥2 (𝑛)}
It is implemented in MATLAB by the array operator ".". Once again the similar restrictions apply for the
.* operator as for the + operator. Therefore we have developed the sigmult function, which is similar to
the sigadd function. Complete the function.

function [y,n] = sigmult(x1,n1,x2,n2)


% imp1ements y(n) - x1(n)*x2(n)
% -----------------------------
% [y,n] = sigmu1t(x1,n1,x2,n2)
% y = product sequence over n, which inc1udes n1 and n2
% x1 = first sequence over n1
% x2 = second sequence over n2 (n2 can be different from n1)

Learning Outcomes

Addition and multiplication of signals in Matlab

Questions

Exercise 1: Let 𝑥1 [𝑛] = 1 1 ≤ 𝑛 ≤ 9 . 𝑥2 [𝑛] = 1 1 ≤ 𝑛 ≤ 20 Generate and plot the following


sequences.
a) 𝑥[𝑛] = 2𝑥1 [𝑛] + 3𝑥2 [𝑛]
b) 𝑥[𝑛] = 3. 𝑥1 [𝑛]. 𝑥2 [𝑛]

Exercise 2: The reflection of signal (flipped version of a signal) is generally encountered in signal
processing. Write a function rx_signal(n,x) such that it plots the flipped version of the original signal x
with duration n. You can use the inbuilt function fliplr(n,x )of Matlab.

Exercise 3: Write the Matlab script to shift a signal to 3 time untis to right. The signal x is [1,3,6,0]
with time duration [0,1,2,3,4]. Add the original signal to the shifted signal and show the results to your
instructor.
Exercise 4: Add two signals y1 with duration n1 and y2 with duration n2 such that:
y1 = [3,-2,2], n1 = [-1,0,1], y2 = [1,0,-1], n2 = [0,1,2]

30
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory 2 = Fair 3= Satisfactory 4 = Very good 5= Excellent

Questions Rating Remarks


(1 to 5)

1. To what extent did you learn on the material in the


lab?

2. Are you able to apply knowledge gained in the lab to


similar problems?

3. Are you able to analyze and interpret data recorded


in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design a system, component or process to


fulfill certain specifications based on the knowledge
acquired in the lab?

6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?

8. Comment whether your work in the lab has an


impact on the society.

Additional Comments (if any):


---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------

31
Lab # 7
Implementation of shifting, folding and scaling of signals

Name: Registration #
Section:

Objective

Implementation of shifting, folding and scaling of signals in MATLAB

Introduction

Shifting: In this operation each sample of 𝑥(𝑛) is shifted by an amount 𝑘 to obtain a shifted sequence
y(n).
𝑦(𝑛) = {𝑥(𝑛 − 𝑘)}
If we let 𝑚 = 𝑛 − 𝑘, then 𝑛 = 𝑚 + 𝑘 and the above operation is given by
𝑦(𝑚 + 𝑘) = {𝑥(𝑚)}
Hence this operation has no effect on the vector x, but the vector n is changed by adding k to each
element. This is shown in the function sigshift.

function [y,n] = sigshift(x,m,n0)


% implements y(n)=(n-n0)
% -------------------------
% [y,n] = sigshift(x,m,nO)
%
n = m+n0
y = x

Folding: In this operation each sample of 𝑥(𝑛) is flipped around 𝑛 = 0 to obtain a folded sequence
𝑦(𝑛).
𝑦(𝑛) = {𝑥(−𝑛)}
In MATLAB this operation is implemented by fliplr(𝑥) function for sample values and by -fliplr(𝑛)
function for sample positions. Complete the following sigfold function.

function [y,n] = sigfold(x,n)


% implements y(n) = x(-n)
% -----------------------
% [y,n] = sigfold(x,n)

32
Scaling: In this operation each sample is multiplied by a scalar a.
{𝑥(𝑛)} = 𝑥(𝑎𝑛)
An arithmetic operator ".*" is used to implement the scaling operation in MATLAB.

Learning Outcomes

Implementation of shifting, folding and scaling of signals in MATLAB

Questions

Exercise # 1: Generate and plot each of the following sequences over the indicated interval.

a) 𝑥(𝑛) = 2𝛿(𝑛 + 2) − 𝛿(𝑛 – 4) − 5 ≤ 𝑛 ≤ 5.

b) 𝑥(𝑛) = 𝑛 [𝑢(𝑛) − 𝑢(𝑛 − 10) + 10𝑒 −0.3(𝑛−10) [𝑢(𝑛 – 10) − 𝑢(𝑛 – 20)]] 0 ≤ 𝑛 ≤ 20

33
c) 𝑥(𝑛) = 𝑐𝑜𝑠(0.04𝜋𝑛) + 0.2𝜔(𝑛) 0 ≤ 𝑛 ≤ 50, where 𝜔(𝑛) is a random sequence.
Hint : use ‘rand’ function to generate random sequence

Exercise # 2: Let 𝑥(𝑛) = {1, 2, 3, 4, 5, 6, 7,6, 5, 4, 3, 2, 1} . Determine and plot the following using the
functions you have implemented in Lab manual.
a) 𝑥1 (𝑛) = 2𝑥(𝑛 − 5) − 3𝑥(𝑛 + 4)
b) 𝑥2 (𝑛) = 𝑥(3 − 𝑛) + 𝑥(𝑛)𝑥(𝑛 − 2)

34
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory 2 = Fair 3= Satisfactory 4 = Very good 5= Excellent

Questions Rating Remarks


(1 to 5)

1. To what extent did you learn on the material in the


lab?

2. Are you able to apply knowledge gained in the lab to


similar problems?

3. Are you able to analyze and interpret data recorded


in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design a system, component or process to


fulfill certain specifications based on the knowledge
acquired in the lab?

6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?

8. Comment whether your work in the lab has an


impact on the society.

Additional Comments (if any):


---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------

35
Lab # 8
Discrete Time Convolution

Name: Registration #
Section:

Objective

Learn how to find convolution of discrete time signals

Introduction

A linear system in which an input-output pair, 𝑥(𝑛) and 𝑦(𝑛), is invariant to a shift 𝑛 in time is called a
linear time-invariant system. The output of an LTI system is given by

𝑦(𝑛) = ∑ 𝑥(𝑘)𝑦(𝑛 − 𝑘)
𝑘= −∞

ℎ(𝑛) is the impulse response of the system. The mathematical operation used in the above equation is
called a linear convolution sum and is denoted by

𝑦(𝑛) ≜ 𝑥(𝑛) ∗ ℎ(𝑛)

MATLAB provides a built in function of conv to calculate the convolution of two functions.

Is the result of mathematical convolution is same as that of MATLAB command conv? No because the
conv function neither provides nor accepts any timing (index) information . What is needed is a beginning
point and an end point of 𝑦(𝑛). If you can determine the index of 𝑦(𝑛) then we can have the correct
results. The starting of the output of the convolution can be calculated by adding the starting indexes of
the input and impulse response. Similarly ending points can be calculated by adding the ending indexes of
the input and impulse response.
Now we can define our own function in MATLAB that is slightly modified from the built in conv
function. Our modified function will use the conv function as underlying function but it will perform
convolution of arbitrary support sequences.

Learning Outcomes

To convolute discrete signals in Matlab.

36
Questions

Exercise #1: Find the convolution y(n) of the two signals mathematically and then by using the
following MATLAB command
>>y =conv(x,h)
Let ;
x(n)= [3,11,7,0¬,-1,4,2] -3≤n≤3;
h(n)= [2,3¬,0,-5,2,1] -1≤¬n≤4
find y[n] using the above command.
Exercise # 2: Complete the code to find out the convolution of above mentioned 𝑥[𝑛] and ℎ[𝑛].

function [y,ny] = conv_m(x,nx,h,nh)


% Modified convolution routine for signal processing
% [y,ny] = conv_m(x,nx,h,nh)
% [y,ny] = convolution result
% [x,nx] = first signal
% [h,nh] = second signal

Exercise # 3: Verify the above result by finding out the convolution of same signals mathematically.

37
Continuous Time Convolution

Objective

To find out the convolution of Continuous Time signals in Matlab

Introduction

In this lab we will study continuous time convolution. The definition of convolution is a mathematical
operation on two functions to generate another function. In signals domain, convolution is the operation
on two signals to generate a new signal. Consider the following system, now in continuous time:

𝒙(𝒕) 𝒚(𝒕)
𝒉(𝒕)

Fig.1

The output 𝑦(𝑡) will be the convolution of input 𝑥(𝑡) and impulse response of the system ℎ(𝑡).

In continuous time convolution we take input, impulse response and the output in continuous time. The
output then is represented by the convolution integral given by:

∞ ∞
y(t) = x(t) ∗ h(t) = ∫−∞ x(τ)h(t − τ)dτ = ∫−∞ h(τ)x(t − τ)dτ

The difference between continuous time convolution and discrete time convolution is that in discrete time
we take samples of our signal but in continuous time we take signal on the whole. It is equivalent to
saying that when we make infinite samples of our signal, then the samples will be very close to each other
and the summation becomes integration and discrete time convolution becomes continuous time
convolution. So in continuous time convolution we use integration rather than summation as described in
the equation above.
In the previous lab we performed convolution using ‘conv’ function. But problem with this built in
function is that is works only if the two signals are discrete time. This function is not defined for
continuous time signals. So, we cannot use ‘conv’ function in the case of continuous time convolution.
There is no built in function for continuous time convolution in MATLAB. Then the obvious question is
how we can perform continuous convolution in MATLAB? The integral used in the above mentioned
expression is the definite integral. MATLAB has a function called INT to perform integration. To explore
this function and its functionality type help symbolic/int and press enter.
Write in your note books what have you understood in "doc syms" & ''doc int ".
Example # 1 Let us take an example regarding continuous time convolution:
Let us consider the convolution of 1/(1+t2) with itself. That is let us calculate
2𝜋
1 1
∫ ∗ 𝑑𝜏
1 + 𝜏 1 + (𝑡 − 𝜏)2
2
−2𝜋
To do this we have MATLAB code

38
syms t tau
f=1/(1+t^2);
z=int(subs(f,tau)*subs(f,t-tau),tau,-2*pi,2*pi)
subplot(2,1,1);
ezplot(f);
xlabel('t');
ylabel('f');
grid on;
title('original signal ');
subplot(2,1,2);
t= -2*pi:0.7:2*pi;
plot(t,subs(z))
xlabel('t');
ylabel('z');
grid on;
title('continuous convolution ');

The function should look like this:

The convolution result is:

Learning Outcomes

Convolution of Continuous Time signals in Matlab

39
Questions

Exercise #1: Consider the input 𝑥(𝑡) = [1 − 𝑒 −1.5𝑡 ] 0 ≤ 𝑡 ≤ 10 and the impulse response be
−𝑡 −3𝑡
ℎ(𝑡) = [2𝑡𝑒 – 𝑒 ], 0 ≤ 𝑡 ≤ 10 and the output is defined as 𝑦(𝑡) = 𝑥(𝑡) ∗ ℎ(𝑡) .:
Write the MATLAB code to find 𝑦(𝑡). Plot 𝑥(𝑡), ℎ(𝑡) and 𝑦(𝑡) in one window.

Exercise #2: Consider the input 𝑥(𝑡) = 𝑐𝑜𝑠(𝑡) , 0 ≤ 𝑡 ≤ 8 and the impulse response be ℎ(𝑡) =
𝑠𝑖𝑛(𝑡) , 0 ≤ 𝑡 ≤ 8and the output is defined as 𝑦(𝑡) = 𝑥(𝑡) ∗ ℎ(𝑡)
Write the MATLAB code to find 𝑦(𝑡). Plot 𝑥(𝑡), ℎ(𝑡) and 𝑦(𝑡) in one window.

Exercise #3: Consider the input 𝑥(𝑡) = 𝑐𝑜𝑠(𝑡) + 𝑡 0 ≤ 𝑡 ≤ 6 and the impulse response be
ℎ(𝑡) = 𝑠𝑖𝑛(𝑡) + 𝑒 2𝑡 0 ≤ 𝑡 ≤ 8 and the output is defined as 𝑦(𝑡) = 𝑥(𝑡) ∗ ℎ(𝑡)
Write the MATLAB code to find 𝑦(𝑡). Plot 𝑥(𝑡), ℎ(𝑡) and 𝑦(𝑡) in one window.

Exercise #4: Consider the input 𝑥(𝑡) = 𝑒 −0.5𝑡 , 0 ≤ 𝑡 ≤ 10 and the impulse response be ℎ(𝑡) =
𝑐𝑜𝑠(𝑡) , 0 ≤ 𝑡 ≤ 10.and the output is defined as 𝑦(𝑡) = 𝑥(𝑡) ∗ ℎ(𝑡)
Write the MATLAB code to find 𝑦(𝑡). Plot 𝑥(𝑡), ℎ(𝑡) and 𝑦(𝑡) in one window.

40
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory 2 = Fair 3= Satisfactory 4 = Very good 5= Excellent

Questions Rating Remarks


(1 to 5)

1. To what extent did you learn on the material in the


lab?

2. Are you able to apply knowledge gained in the lab to


similar problems?

3. Are you able to analyze and interpret data recorded


in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design a system, component or process to


fulfill certain specifications based on the knowledge
acquired in the lab?

6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?

8. Comment whether your work in the lab has an


impact on the society.

Additional Comments (if any):


---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------

41
Lab Manual # 9
Harmonic sequences in Matlab
Name: Registration #
Section:

Objective

To learn sawtooth and square wave form in Matlab, and how to decompose a signal into even and odd
signals.

Introduction

Periodic signals, such as square and sawtoooth waves in a train, etc., are composed of sinusoids forming a
harmonic (or overtone, as used in music) series. A periodic wave, then, is a superposition of sinusoids
having frequencies of 1, 2, 3 ... times a fundamental frequency, with certain specific amplitudes
associated with each harmonic frequency.
A square wave may be synthesized by summing sine waves having only odd harmonics, the amplitudes of
which diminish as the reciprocal of the harmonic number. Equation (6.1) will synthesize a discrete time
square wave having f cycles over a sequence length of N and containing odd harmonics only up to
MaxHar. Note that N, the total number of samples in the signal, must be at least equal to twice the
product of the number of cycles (of square wave) in the sequence and the highest harmonic number to
ensure that there are at least two samples per cycle of the highest frequency present in the synthesized
wave y[n].The requirement that there be at least two samples per cycle of the highest frequency contained
in the signal is a general one imposed on all signals by the properties of the sampling process, and will be
studied in detail in the next labs.

(MaxH_ar+1)/2
y[n] = ∑k=1 (1/(2k − 1)) sin(2πf (2k − 1)(n/N))
For a sawtooth wave, all harmonics are included:

MaxH_ar
1
y[n] = ∑ (k) sin(2πfk)(n/N))
k=1
To illustrate the above formulas in terms of m-code, we will synthesize square and sawtooth waves
having 10 cycles, up to the 99th harmonic.
We compute the necessary minimum sequence length as 2(10)(99) = 1980. The following Math-
Script call will synthesize a square wave up to the 99th harmonic; note that only odd harmonics are
included, i.e., k = 1:2:99.

N=1980;
n = 0:1:N;
y = 0;
for
k = 1:2:99;
y = y + (1/k)*sin(2*pi*10*k*n/N);

42
end
figure;
plot(y);

For a sawtooth wave, the harmonic values are specified as 1:1:99, thus including both odd and
even values:

N=1980;
n = 0:1:N;
y = 0;
for k=1:1:99;
y = y + (1/k)*sin(2*pi*10*k*n/N);
end
figure;
plot(y);

The following figure shows the first three harmonic contents of a square wave.

The following figure illustrates how square wave will look like if it is synthesized form its first five
harmonics.

43
Even and Odd decomposition

Any real sequence can be decomposed into two components that display even and odd symmetry about
the midpoint of the sequence. A sequence that exhibits even symmetry has its first and last samples equal,
its second and penultimate samples equal, and so on. A sequence that exhibits odd symmetry has its first
sample equal to the negative of the last sample, its second sample equal to the negative of its penultimate
sample, etc.
An even decomposition xe of a sequence x can be obtained as:

xe = 0.5*(x + fliplr(x));

and the corresponding odd decomposition xo is:

x0 = 0.5*(x - fliplr(x));

We can write a simple function that generates the even and odd components of an input sequence
x[n] as follows:

function [xe,xo] = evenOdd(x)


xe = (x + fliplr(x))/2;
xo = (x - fliplr(x))/2;

We can illustrate use of the above script with a simple example; assuming that x[n] = [1,3,5,7],we’ll
generate an even/odd decomposition and verify its correctness by summing the even and odd components,
and comparing to the original input signal x[n].

x = [1,3,5,7];
[xe,xo] = evenOdd(x);
re_comb = xe + xo
diff = x – re_comb

From the above we get xe = [4,4,4,4] and xo = [-3,-1,1,3], the sum of which is [1,3,5,7], i.e., the original
sequence x.

Another useful even/odd decomposition is defined such that

xe [n] = xe [-n]

and

xo[n] = -x o[-n]

In this case, the decompositions exhibit their symmetry about n = 0 rather than about the midpoint of the
original sequence x. For example, if x = [1,2,3,4] with corresponding sample indices n = [3,4,5,6], a

44
decomposition about n = 0 can be accomplished by padding x with zeros in such a manner to create a new
sequence with time indices symmetrical about zero. In this case, the new sequence is:

x = [zeros(1,9),1,2,3,4];

having sample indices [-6:1:6]. The new sequence x is then decomposed as above, i.e.,

x = [zeros(1,9),1,2,3,4];
[xe,xo] = LVEvenOdd(x)
recon = xe + xo
diff = x - recon

A script that performs an even-odd decomposition about zero and returns the even and odd parts
and corresponding indices without plotting is

function [xe,xo,m] = even_odd_sym(x,n)


m = -fliplr(n);
m1 = min([m,n]);
m2 = max([m,n]);
m = m1:m2;
nm = n(1)-m(1);
n1 = 1:1:length(n);
x1 = zeros(1,length(m));
x1(n1+nm) = x;
xe = 0.5*(x1 + fliplr(x1));
xo = 0.5*(x1 - fliplr(x1));

The call
[xe,xo,m] = even_odd_sym([1,2,3],[3,4,5])

for example, yields

xe = [1.5,1,0.5,0,0,0,0,0,0.5,1,1.5]
xo = [-1.5,-1,-0.5,0,0,0,0,0,0.5,1,1.5]
m = [-5:1:5]

Outcomes

To learn sawtooth and square wave form in Matlab, and how to decompose a signal into even and odd
signals.

45
Questions

Exercise 1: Write the example codes in m-files and show the results to your instructor.
Exercise 2: Write a code to synthize a square wave form its first five harmonics and show the results to
your instructor
Exercise 3: Write a code to synthesize a square wave from its first nine harmonics and show the results to
your instructor. Explain what the difference between the two synthesized waves.
Exercise 4: Write a function to generate even and odd parts of a signal and plot the results. Generate your
plot for x=0.9.^(0:1:30); for n=[0:1:30];

46
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory 2 = Fair 3= Satisfactory 4 = Very good 5= Excellent

Questions Rating Remarks


(1 to 5)

1. To what extent did you learn on the material in the


lab?

2. Are you able to apply knowledge gained in the lab to


similar problems?

3. Are you able to analyze and interpret data recorded


in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design a system, component or process to


fulfill certain specifications based on the knowledge
acquired in the lab?

6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?

8. Comment whether your work in the lab has an


impact on the society.

Additional Comments (if any):


---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------

47
Lab # 10
Fourier series magnitude and phase calculation in Matlab
Name: Registration #
Section:

Objective

Fourier series, magnitude and phase calculation on Matlab

Introduction

Transforms are used extensively in engineering to change the frame of reference between the time domain
and the frequency domain. Many techniques exist for analyzing steady-state and smoothly changing
systems in the time domain, but complex systems often can be more easily analyzed in other domains.
Fourier series and the Fourier transform play a vital role in many areas of engineering such as
communications and signal processing. These representations are among the most powerful and most
common methods of analyzing and understanding signals. A solid understanding of Fourier series and the
Fourier transform is critical to the design of filters and is beneficial in developing the understanding of
many natural phenomena.
Almost all periodic signals can be represented as an infinite sum of sine and cosines. This sum is called a
Fourier series representation and is defined for a periodic function 𝑥(𝑡) of period T with the following
equation.

𝑎0 2𝜋𝑛𝑡 2𝜋𝑛𝑡
𝑥(𝑡) = + ∑ (𝑎𝑛 cos + 𝑏𝑛 sin )
2 𝑇 𝑇
𝑛=1
Where a0, an and bn are the Fourier series coefficients. These coefficients can be calculated by applying
the following equations:
𝑇 𝑇
2 2𝜋𝑛𝑡 2 2𝜋𝑛𝑡
𝑎𝑛 = ∫ 𝑥(𝑡) cos dt and 𝑏𝑛 = ∫ 𝑥(𝑡) sin dt
𝑇 𝑇 𝑇 𝑇
0 0
If the Fourier coefficients are written as a single complex number 𝑐𝑛 with real part representing the
coefficients of the cosine series and imaginary parts representing coefficients of the sine series, we can
write the complex form of the Fourier series as

1 𝑇
𝑥(𝑡) = ∑+∞
−∞ 𝑐𝑛 𝑒
(𝑗2𝜋𝑛𝑡/𝑇)
where 𝑐𝑛 = ∫ 𝑥(𝑡) 𝑒 −𝑗2𝜋𝑛𝑡/𝑇
𝑇 0
𝑛 = 0, 1, 2. . . .

Fourier series of Saw Tooth Wave

Plot of saw tooth wave

In this section we take an arbitrary saw tooth wave and plot it. Next we plot the magnitude and phase of
the Fourier co-efficient. Then reconstruct the saw tooth wave by combining various harmonics.

48
x = [0.1 0.9 0.1]; % 1 period of x(t)
x = [x x x x]; % 4 periods of x(t)
tx = [-2 -1 0 0 1 2 2 3 4 4 5 6]; % time points for x(t)
plot (tx , x );
grid;
xlabel('Time (sec)');
ylabel('Amplitude ');
title ('Periodic Signal x(t)');
axis ([-2 6 0 1]);

Figure 1

Magnitude and Phase Plot

a0 = 0.5; % DC component of Fourier series


ph0 = 0;
n = [1 3 5 7 9]; % value of n to be evaluated
an = -pi./ ( pi * n ) .^2 ; % Fourier Series C officients
mag_an = abs (an);
phase_an = -180 * ones (1, length (n));
n = (n);
mag_an = [mag_an]; % including a0 with a_n;
phase_an = [phase_an];
figure (2);
clf;
subplot (2, 1 , 1);
plot (n, mag_an, 'o');

49
grid;
xlabel('Harmonic Number');
ylabel ('Magnitude');
title (' Fourier Series Magnitude ');
axis ( [ 0 10 0 0.6 ] );
subplot ( 2 , 1, 2);
plot (n,phase_an, 'o');
grid;
xlabel( 'Harmonic Number');
ylabel ('Phase (radians)');
title ('Fourier Series Phase ');

Figure 2

Computes discrete fourier series

function [Xk]=dfs(xn,N) %computes discrete fourier series coefficients


n=[0:1:N-1];
k=[0:1:N-1];
WN=exp(-j*2*pi/N);
nk=n'*k;
WNnk=WN.^nk;
Xk=xn*WNnk;
End

50
Questions

Exercise #1: Consider the signals given below 𝑥1 (𝑛) = [2,0,2,0] 𝑁 = 4; and 𝑥2 (𝑛) =
[2,0,2,0] 𝑁 = 4. Write the MATLAB code given above for DFS and calculate Xk. Plot 𝑥1 (𝑛), 𝑥2 (𝑛)
and 𝑋𝑘1 (𝑛) and 𝑋𝑘2 (𝑛) in one window. (Hint: Use subplot).

Exercise # 2: Let 𝑥(𝑡) = 𝑠𝑖𝑛(𝑡)with 𝑇 = 2𝜋, then find out the values of 𝒂𝒏 , 𝒃𝒏 , and calculate 𝒙(𝒕).
0 ≤ 𝑡 ≤ 2𝜋 , write its matlab code below.
Exercise # 3: Consider the signals given below

−0.3𝑛
𝑥1(𝑛) = { 𝑛𝑒 , 0 ≤ 𝑛 ≤ 25 , 𝑁 = 50
0 26 ≤ 𝑛 ≤ 49
And
−0.3𝑛
𝑥2(𝑛) = { 𝑛𝑒 , 0 ≤ 𝑛 ≤ 25 , 𝑁 = 100
0 26 ≤ 𝑛 ≤ 99

 Call DFS function used in TASK3 and calculate Xk1,and Xk2;


 stem 𝑥1 (𝑛), 𝑥2 (𝑛) and 𝑋𝑘1 (𝑛) and 𝑋𝑘2 (𝑛)in one window.

51
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory 2 = Fair 3= Satisfactory 4 = Very good 5= Excellent

Questions Rating Remarks


(1 to 5)

1. To what extent did you learn on the material in the


lab?

2. Are you able to apply knowledge gained in the lab to


similar problems?

3. Are you able to analyze and interpret data recorded


in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design a system, component or process to


fulfill certain specifications based on the knowledge
acquired in the lab?

6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?

8. Comment whether your work in the lab has an


impact on the society.

Additional Comments (if any):


---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------

52
Lab Manual # 11
Continuous time Fourier Transform

Name: Registration #
Section:

Objective

To observe continuous time Fourier Transform of signals in Matlab

Introduction

We can then extend the ideas of frequency decomposition to non-periodic signals via the Fourier
Transform. A Fourier transform can be used to analyze a circuit in the frequency domain much like the
Laplace transform can be used to analyze circuits in the s domain. The Fourier transform is defined by
+∞ +∞
−𝑗𝜔𝑡
1
𝑋(𝑗𝜔) = ∫ 𝑥(𝑡)𝑒 𝑑𝑡 ; 𝑥(𝑡) = ∫ 𝑋(𝑗𝜔) 𝑒 𝑗𝜔𝑡 𝑑𝜔
2𝜋
−∞ −∞
MATLAB uses the fourier and ifourier functions to transform expressions between domains. Write the
following commands in MATLAB and understand them.
>>help fourier
>>help ifourier

Example # 1 Write the following code in MATLAB

>>syms t
>>x1 = t*exp(-t.^2)
>>f1 = fourier(x1)
>> if1=ifourier( f1 , 't' )
>>ezplot(f1)
Note the output of the above code in your note book.
Often when using the Fourier transform to solve engineering problems, expressions can include a step
function u(t) and/or impulse function δ(t).

Example # 2 Consider the signal


𝑥2 (𝑡) = −𝑒 −𝑡 𝑢(𝑡) + 3𝛿(𝑡)

The Fourier transform can be found by using following code:

>>x2=-exp(-t) * heaviside(t) + 3 * dirac(t)


>>f2=fourier( -exp(-t) * heaviside(t) + 3 * dirac(t) )
>>pretty (f2)
>>if2=ifourier(f2 , 't' )
>>pretty(if2)
>>ezplot(f2)

53
Note the output of the above code in your note book.
Example # 2 Consider the signal
2
𝑆𝑔𝑛 (𝑡) <— — > ∗𝑤
𝑗
Write the following code in MATLAB

>>x3 = heaviside (t) - heaviside (- t);


>>f3 = fourier (x3)
>> ezplot (abs(f3))

Figure 1
>> ezplot ( abs (f3) , [ -10 10] )

Figure 2
>> syms w
>> ezplot ( w , abs ( f3) , [ -5 5 -10 10 ] )

54
Figure 3
>> axis ( [ -5 5 -10 10 ] );

Figure 4
Explain the difference in the above three plots in your note book???

Learning Outcomes

The relationship between the time and frequency domains as shown by performing Fourier analysis of
assigned signals.

Questions:

Exercise # 1: Plot the Fourier and its inverse transforms of: 𝑒 –𝑎𝑡 𝑢 (𝑡).
Exercise # 2: Plot the Fourier and its inverse transforms of: 𝑠𝑖𝑛(𝑡) ∗ 𝑒 –10𝑡 𝑢 (𝑡).

55
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory 2 = Fair 3= Satisfactory 4 = Very good 5= Excellent

Questions Rating Remarks


(1 to 5)

1. To what extent did you learn on the material in the


lab?

2. Are you able to apply knowledge gained in the lab to


similar problems?

3. Are you able to analyze and interpret data recorded


in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design a system, component or process to


fulfill certain specifications based on the knowledge
acquired in the lab?

6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?

8. Comment whether your work in the lab has an


impact on the society.

Additional Comments (if any):


---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------

56
Lab # 12
Discrete time Fourier Transform

Name: Registration #
Section:

Objective

To observe Discrete time Fourier Transform of signals in Matlab

Introduction

We have seen how a linear and time-invariant system can be represented using its response to the unit
sample sequence. This response, called the unit impulse response ℎ(𝑛), allows us to compute the system
response to any arbitrary input 𝑥(𝑛) using the linear convolution as shown below.

This convolution representation is based on the fact that any signal can be represented by a linear
combination of scaled and delayed unit samples. Similarly, we can also represent any arbitrary discrete
signal as a linear combination of basis signals introduced in previous lab manuals. Each basis signal set
provides a new signal representation. Each representation has some advantages and some disadvantages
depending upon the type of system under consideration. However, when the system is linear and time-
invariant, only one representation stands out as the most useful. It is based on the complex exponential
signal set 𝑒 𝑗𝜔𝑛 and is called the Discrete-time Fourier Transform.

Discrete-time Fourier transform (dtft)

If 𝑥(𝑛) is absolutely sum able, that is ∑∞


−∞|𝑥(𝑛)| < ∞ , then its discrete-time Fourier transform is given
by

𝑗𝜔
𝑋(𝑒 ) = ∑ 𝑥(𝑛)𝑒 𝑗𝑤𝑛
𝑛=−∞
The DTFT transforms a discrete signal 𝑥(𝑛) into a complex-valued continuous function 𝑋(𝑒 𝑗𝜔 ) of real
variable 𝜔, called a digital frequency, which is measured in radians.
We will state the following two important properties:

Periodicity: The discrete-time Fourier transform 𝑋(𝑒 𝑗𝜔 ) is periodic in 𝜔 with period 2𝜋.
𝑋(𝑒 𝑗𝜔 ) = 𝑋(𝑒 𝑗(𝜔+2𝜋) )

57
Implication: We need only one period of (𝑒 𝑗𝜔 ) (𝑖. 𝑒. 𝜔 ∈ [𝑂, 2𝜋], 𝑜𝑟 [−𝜋, 𝜋]) for analysis and not the
whole domain −∞ < 𝜔 < ∞ .
Symmetry: For real-valued 𝑥(𝑛), 𝑋(𝑒 𝑗𝜔 ) is conjugate symmetric.
𝑋(𝑒 −𝑗𝜔 ) = 𝑋 ∗ (𝑒 𝑗𝜔 )
or
𝑅𝑒[𝑋(𝑒 −𝑗𝜔 )] = 𝑅𝑒[𝑋(𝑒 𝑗𝜔 )] (even symmetry)
−𝑗𝜔 −𝑗𝜔
𝐼𝑚[𝑋(𝑒 )] = −𝐼𝑚[𝑋(𝑒 )] (odd symmetry)
−𝑗𝜔 −𝑗𝜔
|𝑋(𝑒 ) | = |𝑋(𝑒 )| (even symmetry)
−𝑗𝜔 𝑗𝜔
∠𝑋(𝑒 ) = −∠𝑋(𝑒 ) (odd symmetry)

Implication:

To plot 𝑋(𝑒 𝑗𝜔 ) ,we now need to consider only a half period of 𝑋(𝑒 𝑗𝜔 ) .Generally, in practice this period
is chosen to be 𝜔 𝜖 [0, 𝜋].

NOTE: If 𝑥(𝑛) is of infinite duration, then MATLAB cannot be used directly to compute 𝑋(𝑒 𝑗𝜔 ) from
𝑥(𝑛). However, we can use it to evaluate the expression 𝑋(𝑒 𝑗𝜔 ) over [0, 𝜋] frequencies and then plot its
magnitude and angle (or real and imaginary parts).

Example # 1 Find the discrete-time Fourier transform of 𝑥(𝑛) = (0.5)𝑛 𝜇[𝑛] mathematically using
formula.

𝑋(𝑒−𝑗𝜔 ) =
Now write the following code in script file and run.

w = [0:1:500]*pi/500; % [0, pi] axis divided into 501 points.


X = exp(1i*w) ./ (exp(1i*w) - 0.5*ones(1,501));
magX = abs(X);
angX = angle(X);
realX = real(X);
imagX = imag(X);
subplot(2,2,1);
plot(w/pi,magX);
grid
xlabel('frequency in pi units');
title('Magnitude Part');
ylabel('Magnitude')
subplot(2,2,3);
plot(w/pi,angX);
grid
xlabel('frequency in pi units');
title('Angle Part');
ylabel('Radians');
subplot(2,2,2);
plot(w/pi,realX);

58
grid
xlabel('frequency in pi units');
title('Real Part');
ylabel('Real')
subplot(2,2,4);
plot(w/pi,imagX);
grid
xlabel('frequency in pi units');
title('Imaginary Part');
ylabel('Imaginary');

Note that we divided the 𝜔 array by pi before plotting so that the frequency axes are in the units of 𝜋 and
therefore easier to read. This practice is strongly recommended.
Numerically compute the discrete-time Fourier transform of the sequence 𝑥(𝑛) = {𝐼, 2, 3, 4, 5} given in
501 equi-spaced frequencies between [0, 𝜋].

𝑗𝜋𝑛
Example # 2 Let 𝑥(𝑛) = 0.9 𝑒 3 , 0 ≤ 𝑛 ≤ 10. Determine 𝑋(𝑒 𝑗𝜔 ) mathematically and then
implement its code as we have done in example # 1. Investigate the periodicity of Fourier transform.

Mathematically :

MATLAB code :

59
Example # 3 Let x( 𝑛) = 2𝑛 , − 10 ≤ 𝑛 ≤ 10. Investigate the conjugate symmetry property of its
discrete time Fourier transform.
Mathematically:

MATLAB code:

Learning Outcome

The relationship between the time and frequency domains as shown by performing Fourier analysis of
assigned signals.

60
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory 2 = Fair 3= Satisfactory 4 = Very good 5= Excellent

Questions Rating Remarks


(1 to 5)

1. To what extent did you learn on the material in the


lab?

2. Are you able to apply knowledge gained in the lab to


similar problems?

3. Are you able to analyze and interpret data recorded


in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design a system, component or process to


fulfill certain specifications based on the knowledge
acquired in the lab?

6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?

8. Comment whether your work in the lab has an


impact on the society.

Additional Comments (if any):


---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------

61
Lab # 13
Properties of Fourier Transform

Name: Registration #
Section:

Objective

To observe properties of Fourier Transform of signals in Matlab

Introduction

Discrete-time Fourier transform (dtft)

If 𝑥(𝑛) is absolutely summable, that is ∑∞


−∞|𝑥(𝑛)| < ∞ , then its discrete-time Fourier transform is given
by

𝑗𝜔
𝑋(𝑒 ) = ∑ 𝑥(𝑛)𝑒 −𝑗𝜔𝑛
𝑛=−∞
The DTFT transforms a discrete signal 𝑥(𝑛) into a complex-valued continuous function 𝑋(𝑒 𝑗𝜔 ) of real
variable 𝜔, called a digital frequency, which is measured in radians.

Following function can be used to find out dtft of any time domain signal.

function [magX,angX,realX,imagX] = dtft(x,n)


w= ([0:500]/500)*2*pi;
X = x * (exp(-1*i*n'*w));
magX = abs(X);
angX = angle(X);
realX = real(X);
imagX = imag(X);
subplot(2,2,1);
plot(w/pi,magX);
grid
xlabel('frequency in pi units');
title('Magnitude Part');
ylabel('Magnitude')
subplot(2,2,3);
plot(w/pi,angX);
grid
xlabel('frequency in pi units');
title('Angle Part');
ylabel('Radians');
subplot(2,2,2);
plot(w/pi,realX);

62
grid
xlabel('frequency in pi units');
title('Real Part');
ylabel('Real')
subplot(2,2,4);
plot(w/pi,imagX);
grid
xlabel('frequency in pi units');
title('Imaginary Part');
ylabel('Imaginary');

Properties of DTFT

The following table summarizes the properties of DTFT

Figure 1 Properties of DTFT (Source: Digital Signal Processing by John .G. Proakis)

Learning Outcome

Students will be able to learn about the properties of discrete time Fourier transform in Matlab.

63
Questions

Exercise # 1: Verify the linearity property using real-valued finite-duration sequences. Let 𝑥1 (𝑛) and
𝑥2 (𝑛) be two random sequences uniformly distributed between [0, 1] over 0 ≤ 𝑛 ≤ 10.

xl = rand(1,11);
x2 = rand(1,11);
n = 0:10;
alpha = 2;
beta = 3;
k = 0:500;
w = (pi/500)*k;
X1 = xl * (exp(-j*pi/500)).^(n'*k); % DTFT of xl
X2 = x2 * (exp(-j*pi/500)).^(n'*k); % DTFT of x2
x = alpha*xl + beta*x2; % Linear combination of xl t; x2
X = x * (exp(-j*pi/500)).^(n'*k); % DTFT of x
% verification
X_check = alpha*X1 + beta*X2; % Linear Combination of Xl & X2
error = max(abs(X-X_check))

Exercise # 2: Let 𝑥(𝑛) be a random sequence uniformly distributed between [0,1] over 0 ≤ 𝑛 ≤ 10 and
let 𝑦(𝑛) = 𝑥(𝑛 − 2). Then we can verify the sample shift property. Write code in your note book and
plot.

𝜋𝑛
Exercise # 3: Verify the frequency shift property graphically Let 𝑥(𝑛) = 𝑐𝑜𝑠 ( 2 ) , 0 ≤ 𝑛 ≤ 100 𝑎𝑛𝑑
𝑦(𝑛) = 𝑒 𝑗𝜋𝑛/4 𝑥(𝑛). Write code in your note book and plot.

64
Exercise # 4 : Verify the
i. conjugation property
ii. folding property

let 𝑥(𝑛) be a complex-valued random sequence over −5 ≤ 𝑛 ≤ 10 with real and imaginary parts
uniformly distributed between [0,1]. Write code in your note book and plot.

65
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory 2 = Fair 3= Satisfactory 4 = Very good 5= Excellent

Questions Rating Remarks


(1 to 5)

1. To what extent did you learn on the material in the


lab?

2. Are you able to apply knowledge gained in the lab to


similar problems?

3. Are you able to analyze and interpret data recorded


in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design a system, component or process to


fulfill certain specifications based on the knowledge
acquired in the lab?

6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?

8. Comment whether your work in the lab has an


impact on the society.

Additional Comments (if any):


---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------

66
Lab # 14 & 15
SAMPLING, QUANTIZATION AND RECONSTRUCTION OF
BANDLIMITED SIGNALS.

Name: Registration #
Section:

Objective
To demonstrate the time domain sampling of bandlimited signals (Nyquist theorem).
Introduction
SAMPLING
The real life signals that we encounter in our day to day basis are mostly analog signals. These
signals are defined continuously in time and have infinite range of amplitude values. In order to
process these signals to obtain meaningful information, they need to be converted to a format which
is easily handled by computing resources like microprocessors, computers etc... The first step in this
process is to convert the real-time signal into discrete-time signals. Discrete-time signals are defined
only at a particular set of time instances. They can thus be represented as sequence of numbers with
continuous range of values.

The process of converting an analog signal (denoted as x(t)) to a digital signal (denoted as x(n)) is
called the analog-to-digital conversion (referred to as digitization), usually performed by an analog -
to-digital converter (ADC). Here t is the continuous time variable and n is the sequence order. In
many applications after the processing of the digital signal is performed, x(n) needs to be converted
back to analog signal x(t) before it is applied to appropriate analog device. This reverse process is
called digital-to-analog conversion and is typically performed using a digital-to-analog converter
(DAC).

The typical block diagram of an ADC is shown in Fig. 1 below.

The process of digitization consists of first sampling (digitization in time) and quantization
(digitization in amplitude). In this experiment we will study and understand the principle of
sampling, while the principle of quantization will be studied in the next experiment. The sampling
process depicts an analog signal as a sequence of values. The basic sampling function can be carried

67
out with an ideal 'sample-and-hold' circuit which maintains the sampled signal until next sample is
taken. An ideal sampler can be considered as a switch that periodically opens and closes every T
seconds. The sampling frequency (fs in Hertz) is thus defined as,

The sampled discrete time signal x(nT) , n=0,1,2,.... of the original continuous time signal x(t) is
shown in Fig. 2 below.

In order to represent an analog signal x(t) by a discrete-time signal x(nT) accurately, so that the
analog signal can be exactly reconstructed back from the discrete-time signal, the sampling
frequency fs must be at least twice the maximum frequency component (fM) of the original analog
signal. Thus we have,

The minimum sampling rate is called the Nyquist rate and the above Sampling Theorem is called the
Shannon's Sampling Theorem. When an analog signal is sampled at fs , frequency components
higher than fs/2 fold back into the frequency range [0, fs/2]. This folded frequency components
overlap with the original frequency components in the same range and leads to an undesired effect
known as aliasing. In this case, the original analog signal cannot be recovered from the sample
data.

Consider an analog signal of frequency 1 Hz as shown in Fig. 3(a) below. The sampling freq uency
is 4 Hz. The sampled signal is shown in Fig. 3(b), Note that an exact reconstruction of the missing
samples is obtained so long as the Shannon's Sampling Theorem is satisfied.

68
Now let's consider, the analog signal of frequency 5 Hz as shown in Fig. 4(a) below. The sampling
frequency is same as above, i.e. 4 Hz. The sampled signal is shown in Fig. 4(b), Note that the
reconstruction of the original analog signal is not possible since the sampling frequency does not
satisfy Shannon's Sampling Theorem. In this case the reconstructed signal has a frequency of 1 Hz.
The signal of 5 Hz is folded back as 1 Hz, into the range determined by the sampling frequency
leading to the problem of aliasing.

QUANTIZATION

A discrete time signal is the sampled version of the continuous-time signal, which can theoretically
still take on any value within a certain range of values. Thus the next step to convert a discrete -time
signal to a digital signal is by restricting the amplitude to certain fixed values from a discrete set.
This process is known as quantization and the number of elements in the discrete set is known as the
quantization levels. The quantized signal loses information due to rounding-off and thus are only an
approximation to the continuous-time signals. The difference between the quantized signal and the
continuous amplitude signal is known as quantization noise.

A sample input-output characteristic of an uniform quantizer is shown in Fig. 1 below.

69
Here y is the continuous amplitude of the signal within the range of [-4,4]. Any value less than -4, is
mapped to the digit d1. Any value between the range [-4,-3] is mapped to the digit d2. Any value
within the range of [1,2] is mapped to the digit d7. This kind of quantizer is known as mid tread
quantizer.

Digital systems like computers however do not represent numbers using decimal digits. Instead they
use binary system of representation. Each number there is represented by a binary digit - known as
bits. With 'b' bits, we can represent 2b distinct numbers.
In the above example, the quantized sits at the mid-point of a particular range i.e. [-4, -3] essentially
is represented by a quantized value -3.5, the range [-3, -2] by -2.5 and so on. This gives rise to error
known as quantized error. The number of such ranges available with b bits of quantization is 2b.
Let us define step size i.e. width of each level as Δ.
Let us further define quantization error e(t) = f(t) - fq(t) where the analog signal is f(t) and its
quantized version isfq(t). Then e(t) lies within the range ±Δ/2. The range of the analog signal that
can be covered by b bits within above error range, R = 2b.Δ

If the quantization error is uniformly distributed about ±Δ/2 then


Then Mean Square Error (MSE) for the quantization process, also known as quantization noise
power is given by

Nq =

70
Now, if the range or maximum excursion of the analog signal is fixed then we can write, .
We can see that increasing the value of b or the no. of bits Nq decreases.
Let us further investigate the effect of no. of bits used in quantization by assuming the input signal
is sinusoidal with amplitude A.

Then signal power, S =

Also, R = 2A thus

Substituting, Signal to Noise Ratio, SNR = 10 log10 = 10 log10 (6.22b – 2) ≈ 6.b dB


Thus each additional bit improves SNR by 6 dB.
MATLAB CODE
Write the following code in MATLAB editor and execute it.

% Example of sampling, quantization, and zero-order hold


close all; clear all; clc;
td=0.002; % original sampling rate 500 Hz
t=0:td:1;
xsig=sin(2*pi*t)-sin(6*pi*t); % 1Hz+3Hz sinusoids
Lsig=length(xsig);

ts=0.02; % new sampling rate = 50Hz


Nfactor=ts/td;
% send the signal hrough a 16-level uniform quantizer
[s_out,sq_out,sqh_out,Delta,SQNR]=sampandquant(xsig,16,td,ts);
% receive 3 signals:
% 1. sampled signal s_out
% 2. sampled and quantized signal sq_out
% 3. sampled, quantized, and zero-order hold signal sqh_out
% calculate the Fourier transforms
Lfft=2^ceil(log2(Lsig)+1);
Fmax=1/(2*td);
Faxis=linspace(-Fmax,Fmax,Lfft);
Xsig=fftshift(fft(xsig,Lfft));
S_out=fftshift(fft(s_out,Lfft));
% Examples of sampling and reconstruction using
% (a) ideal impluse train through LPF
% (b) flat top pulse reconstruction through LPF
% plot the roginal signal and the sample signals in time and frequency
% domain.
figure(1);
subplot(311); sfigla=plot(t,xsig,'k');
hold on; sfig1b=plot(t,s_out(1:Lsig),'b');hold off;
set(sfigla,'Linewidth',2); set(sfig1b,'Linewidth',2.);
xlabel('time (sec)');
title('Signal {\it g} (\it t) and its uniform samples');
subplot(312);sfig1c=plot(Faxis,abs(Xsig));
xlabel(' frequency (Hz)');

71
axis([-150 150 0 300]);
set(sfig1c,'Linewidth',1); title('Spectrum of {\it g}({\it t})');
subplot(313); sfig1d=plot(Faxis,abs(S_out));
xlabel('frequency (Hz)');
axis([-150 150 0 300/Nfactor]);
set(sfig1c,'Linewidth',1); title('Spectrum of {\it g}_T({\it t})');

% calculate the reconstructed signal from ideal sampling and ideal LPF
% Maximum LPF bandwidth equals to BW=floor((Lfft/Nfactor)/2);
BW=10; % Bandwidth is no larger than 10Hz
H_lpf=zeros(1,Lfft); H_lpf(Lfft/2-BW:Lfft/2+BW-1)=1; %ideal LPF
S_recv=Nfactor*S_out.*H_lpf; % ideal filtering
s_recv=real(ifft(fftshift(S_recv)));% reconstructed f-domain
s_recv=s_recv(1:Lsig); % reconstructed t-domian
% plot the ideally reconstructed signal in time and frequency domain
figure(2)
subplot(211); sfig2a=plot(Faxis,abs(S_recv));
xlabel('frequency (Hz)');
axis([-150 150 0 300]);
title('Spectrum of ideal filtering (reconstruction)');
subplot(212); sfig2b=plot(t,xsig,'k-.',t,s_recv(1:Lsig),'b');
legend('Original signal','Reconstructed signal');
xlabel('time (sec)');
title('Original signal versus ideally reconstructed signal');
set(sfig2b,'Linewidth',2);
% noe-ideal reconstruction
ZOH=ones(1,Nfactor);
s_ni=kron(downsample(s_out,Nfactor),ZOH);
S_ni=fftshift(fft(s_ni,Lfft));
S_recv2=S_ni.*H_lpf; % ideal filtering
s_recv2=real(ifft(fftshift(S_recv2))); % reconstructed f-domain
s_recv2=s_recv2(1:Lsig); % reconstructed t-domain

% plot the ideally reconstructed signal in time and frequency domain


figure(3)
subplot(211); sfig3a=plot(t,xsig,'b',t,s_ni(1:Lsig),'b');
xlabel('time (sec)');
title('original signal versus flat-top reconstruction');
subplot(212);sfig3b=plot(t,xsig,'b',t,s_recv2(1:Lsig),'b--');
legend('Original signal','LPF reconstruction');
xlabel('time(sec)');
set(sfig3a,'Linewidth',2); set(sfig3b,'Linewidth',2);
title('original and flat-top recosntruction after LPF');

72
% (sampandquant.m)
function [s_out,sq_out,sqh_out,Delta,SQNR]=sampandquant(sig_in,L,td,ts)
% Usage
% [s_out,sq_out,sqh_out,Delta,SQNR]=sampandquant(sig_in,L,td,ts)
% L - number of uniform quantization levels
% sig_in - input signal vector
% td - original signal sampling period of sig_in
% ts - new sampling period
% NOTE: td*fs must be a positive integer;

% Function outputs:
% s_out - sampled output
% sq_out - sample-and-quantized output
% sqh_out - sample,quantize, and hold output
% Delta - quantization interval
% SQNR - actual signal to quantization noise ratio

if (rem(ts/td,1)==0)
nfac=round(ts/td);
p_zoh=ones(1,nfac);
s_out=downsample(sig_in,nfac);
[sq_out,Delta,SQNR]=uniquan(s_out,L);
s_out=upsample(s_out,nfac);
sqh_out=kron(sq_out,p_zoh);
else
warning('Errors! ts/td is not an integer!');
s_out=[];sq_out=[];sqh_out=[];Delta=[];SQNR=[];
end
end

% (uniquan.m)
function [q_out, Delta,SQNR]=uniquan(sig_in,L)
% Usage
% [q_out, Delta,SQNR]=uniquan(sig_in,L)
% L - number of uniform quantization levels
% sig_in - input signal vector
% Function ouputs:
% q_out - quantized output
% Delta - quantization interval
% SQNR - actual signal to quantization noise ratio
sig_pmax=max(sig_in);% finding the positive peak;
sig_nmax=min(sig_in);% finding the negative peak
Delta=(sig_pmax-sig_nmax)/L; % quantization interval
q_level=sig_nmax+Delta/2:Delta:sig_pmax-Delta/2;% dfine Q-levels
L_sig=length(sig_in); % find signal length
sigp=(sig_in-sig_nmax)/Delta+1/2;% convert into 1/2 to L+1/2 range
qindex=round(sigp); % round to 1,2,... L levels
qindex=min(qindex,L); % eleminate L+1 as a rare possibility
q_out=q_level(qindex);% use index vector to generate output
SQNR=20*log10(norm(sig_in)/norm(sig_in-q_out));% actual SQNR value
end

73
Learning Outcomes

Students will be able to learn basics of sampling and quantization using Matlab.

Questions
1) With increasing sampling frequency fs, the mean square error of the reconstructed output w.r.t the
original signal

increases.
remains uneffected.
almost zero.
remains constant after initial
decrease.

2) The main cause of aliasing distortion observed in frequency domain in sampling of a continuous time signal is
the signal spectra being band-limited.
the signal spectra being non band-limited.
sampling in time domain.

3) Linear interpolation based reconstruction process


maintains the value of the previous sampling instant till next sampling instant.
joins the adjacent sampling points by a straight line.
joins the adjacent sampling points by a second-order polynomial.

4) What is over sampling ?


Sampling a signal with sampling frequency significantly higher than the bandwidth of the signal being sampled.
Sampling a signal with sampling frequency significantly lower than the bandwidth of the signal being sampled.
Sampling a signal with sampling frequency significantly higher than twice the bandwidth of the signal being sampled.

74
Sampling a signal with sampling frequency three times higher than the bandwidth of the signal being sampled.

5) What do you mean by under sampling ?


Sampling the signal at Nyquist rate.
Sampling the signal below the Nyquist rate.
Sampling the signal greater than or equal to Nyquist rate.

6) What is the use of anti-aliasing filter ?


It is used for reconstruction of a signal.
It is used to restrict the bandwidth of a signal to satisfy the sampling theorem and to prevent aliasing.

7) A signal can be reconstructed from its samples by using which method?


Filtering.
Resampling.
Auto-correlation.

75
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory 2 = Fair 3= Satisfactory 4 = Very good 5= Excellent

Questions Rating Remarks


(1 to 5)

1. To what extent did you learn on the material in the


lab?

2. Are you able to apply knowledge gained in the lab to


similar problems?

3. Are you able to analyze and interpret data recorded


in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design a system, component or process to


fulfill certain specifications based on the knowledge
acquired in the lab?

6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?

8. Comment whether your work in the lab has an


impact on the society.

Additional Comments (if any):


---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------

76
Lab # 16
Generation of Different Signals

Name: Registration #
Section:

Objective

The objective of this lab is to introduce students to the Matlab environment, generate some basic signals
in Matlab and also using basic op-amp circuit. And Handling these signals using function generators and
spectrum analyzer.

Introduction

The MATLAB® high-performance language for technical computing integrates computation,


visualization, and programming in an easy-to-use environment where problems and solutions are
expressed in familiar mathematical notation.
MATLAB is an interactive system which allows you to solve many technical computing problems. The
name MATLAB stands for matrix laboratory. MATLAB was originally written to provide easy access to
matrix software developed by the LINPACK and EISPACK projects. Today, MATLAB engines
incorporate the LAPACK and BLAS libraries, embedding the state of the art in software for matrix
computation.

The MATLAB System

The MATLAB system consists of these main parts:

Desktop Tools and Development Environment

This part of MATLAB is the set of tools and facilities that help you use and become more productive with
MATLAB functions and files. Many of these tools are graphical user interfaces. It includes: the
MATLAB desktop and Command Window, an editor and debugger, a code analyzer, and browsers for
viewing help, the workspace, and folders.

Mathematical Function Library

This library is a vast collection of computational algorithms ranging from elementary functions, like sum,
sine, cosine, and complex arithmetic, to more sophisticated functions like matrix inverse, matrix Eigen
values, Bessel functions, and fast Fourier transforms.

The Language

77
The MATLAB language is a high-level matrix/array language with control flow statements, functions,
data structures, input/output, and object-oriented programming features. It allows both “programming in
the small” to rapidly create quick programs you do not intend to reuse. You can also do “programming in
the large” to create complex application programs intended for reuse.

Graphics
MATLAB has extensive facilities for displaying vectors

Basic operations in MATLAB


Operators

Expressions use familiar arithmetic operators and precedence rules.


+ Addition
- Subtraction
* Multiplication
/ Division
^ Power
' Complex conjugate transpose
.* Element-by-element multiplication
./ Element-by-element division
.^ Element-by-element power-

Examples:
If a = 23, b = 9
Find a + b.
>> a= 23
>>b=9
>> a+b
Write your output.
Basic Signals

The sinusoidal signals of Different frequencies can be generated and plotted in Matlab
environment.
Examples:
Following commands will generate a sin wave of frequency of 30 Hz.
t=0:.001:10;
y=sin (2*pi*30*t)
Plot(y) %plots the sin wave spectrum
The sinusoidal signal can be generated using the function generators or by using the basic
oscillators circuits.

78
Practical Work:
To generate a sin wave, design a op amp circuit, the circuit which is to be implemented in lab is a three
stage circuitry, first we will produce a square wave, in next stage a triangular wave is produced and
finally we will get the sin wave.

Stage#1
In first stage, It is used just as a comparator. A fraction of output is fed back to the non-inverting (+)
terminal as reference voltage. The capacitor C can charge through the trim pot R.
When the output is high, the capacitor C starts charging and once if the voltage across the capacitor
reaches the reference voltage, the output is driven to negative region.
The capacitor now charges with negative polarity and once it reaches reference voltage, the output is
driven to positive region.
This cycle continues and a square wave is obtained as output.
The frequency of this oscillation is given by F= 1/(2RC).
Therefore, by varying the trim pot R the frequency can be changed.

79
Stage #2:

Our output of this stage is a triangular wave form which is shows in fig.

Stage 3:
In 3rd stage we get the original required output which is a sine wave and it shows in fig4.

80
Learning Outcomes

Introduction of Matlab and its basic mathematical operations.


Generation of different signals in Matlab.
Generation of different sinusoidal signals using op-amp

Questions

Exercise # 1: Evaluate a-b, a*b, a/b and a ^ b. Write all commands and outputs in your note
books.
Exercise # 2: Evaluate a.*b, a. /b, a. ^b. Write all commands and outputs in your note books.
Exercise # 3: Generate a square wave of any function.
Exercise # 3: Find out the difference between a*b and a.*b.

81
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory 2 = Fair 3= Satisfactory 4 = Very good 5= Excellent

Questions Rating Remarks


(1 to 5)

1. To what extent did you learn on the material in the


lab?

2. Are you able to apply knowledge gained in the lab to


similar problems?

3. Are you able to analyze and interpret data recorded


in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design a system, component or process to


fulfill certain specifications based on the knowledge
acquired in the lab?

6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?

8. Comment whether your work in the lab has an


impact on the society.

Additional Comments (if any):


---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------

82

Вам также может понравиться