You are on page 1of 98

Signals and Systems

Using Matlab Toolbox


Computer Laboratory Workbook / Manual

First Edition 2014

S K Hasnain
Sqn Ldr (R); CEng MIET
Professor and Ex Head of the Department
Swedish College of Engineering and Technology
Rahim Yar Khan, Punjab, Pakistan

Muhammad Usman Sardar


Lab Engineer
Swedish College of Engineering and Technology
Rahim Yar Khan, Punjab, Pakistan

NAME: ______________________________

SEMESTER/YEAR: ___________________________

ROLL NO:_____________________________________

BATCH :_____________________________________

DEPARTMENT:_____________________________________

Royal Book Company


BG-5 Rex Centre, Fatima Jinnah Road
G.P.O. Box 7737, Karachi-75530, Pakistan
Phone: 35653418, 35684244, 35670628, Fax: 35653419
Email: royalbook@hotmail.com
This copy is published by the permission of author

1
Signals and Systems
Using Matlab Toolbox
Computer Laboratory Workbook

By

Syed Khursheed ul Hasnain and Muhammad Usman Sardar

All rights reserved. No part of the publication may be reproduced, stored in retrieval system, or transmitted
in any form or by any means, electronics, and mechanical photo copying, recording or otherwise, without
the prior information of the copy right holders.

This book is sold subject to the condition that it shall not, by way of trade or otherwise, be lent or resold,
hired out or otherwise circulated without publisher prior consent in any form of binding or cover other than
that in which it is published and without a similar condition
including this condition being imposed on the subsequent publisher.

2
First Edition 2014

Published & distributed by:


by Royal Book Company
BG-5 Rex Centre, Fatima Jinnah Road
G.P.O. Box 7737, Karachi-75530, Pakistan
Phone: 35653418, 35684244, 35670628
Fax: 35653419
Email: royalbook@hotmail.com
Printed by: Zaki Sons Printers, Karachi
Composed by Decent Print Enterprises, Phone: 2631302
ISBN: - - - -

Printed in Pakistan

3
In memory of our
parent
who encouraged us to constantly enhance the
boundary of knowledge

4
Preface to First Edition
______________________________________________________________________

In recent years, the subject of Signals and Systems has become so important that it is now taught as a core
subject in almost all the undergraduate courses in engineering throughout the world.

The main objective in developing this Laboratory Workbook is to provide a working knowledge of Signals
and Systems in Matlab for students at undergraduate level. This will help them to understand and simulate
the properties and behaviour of Signal and Systems to comprehend the subject after simulation of different
topics studied in the Signal and Systems course work.

It was our desire to develop a Laboratory Workbook for undergraduate students. Therefore general standard
of this Laboratory workbook is aimed at undergraduate level engineering and computer science students
and application engineers who wish to gain a working knowledge of Signal and Systems from scratch.
No attempt has been made to include graduate level practical exercises; we feel that graduate level topics
are sufficiently present in several books available in the market.

Authors
Acknowledgement

We also wish to express our gratitude to the following for contributing towards our effort:

 Mr. Syed Furrukh Hasnain of Institute of Business Administration, Karachi and Ms. Nighat Jamil M Sc
from Pakistan Navy Engineering College (NUST) for technical support during preparation of this book.
 Mr. Syed Tashfeen Hashmi for designing the cover of this workbook.
 Mr. Shahbaz Ahmad Warya for preparing the Matlab codes, progressive for students.
 Mr. Rauf Ahmad for preparing the contents lists and updates for development of signals and system
course.

Special Features for Students and Instructors

This workbook is Matlab based for illustrating the important ideas and applications in signal processing.
We believe that our effort in using Matlab gives the students more confidence in this subject.
Students and instructors who are not familiar with Matlab should not be apprehensive about using this
workbook to learn Signals and Systems. Matlab is very easy to learn. Furthermore, the help documentation
is available online from Mathworks (http://www.mathworks.com), which is easy to use and contains many
examples and Texas instruments (http://www.ti.com). Our experience has shown that signal processing
students completely unfamiliar with MATLAB are able to use MATLAB within a week or two of exposure
to tutorial exercises.

Any suggestions to improve this workbook would be highly appreciated. Every attempt has been made to
ensure the accuracy of all material in the First Edition of the book. Readers‟ comments and criticism are
welcomed. Any suggestions or error reporting can be sent to hasnain@pnec.edu.pk with a CC to
skhpnec@gmail.com.
Authors

5
About the Authors

S K Hasnain is a graduate of NED university of Engineering and Technology. He has completed his
Doctorate in I T from Preston University is also a member of IET, Chartered Engineer of Engineering
Council UK, and Life member Pakistan Engineering Council, currently a Professor and EX head of the
department at Swedish college of Engineering and Technology, Rahim Yar Khan , Pakistan. He has more
than forty years of teaching experience at university level. He has done his doctorate in Information
Technology. He has three master‟s degree; Applied Mathematics, Electrical Engineering and Information
Technology. He has specialized in Electrical Engineering Control from Cranfield University UK. He is also
the author of Digital Signal Processing Theory and Worked Examples 3rd edition, Digital Signal
Processing Computer Laboratory Workbook Using DSP Toolboxes and Blocksets in MATLAB
including TI TMS320C6713 DSK 3rd edition, Signals and Systems Theory and Worked Examples 1st
edition, Control System Engineering Theory and Worked Examples Control Systems for Engineers,
Theory and Worked Examples 1st edition, Programmable Logic Controller laboratory work book 1st
edition and co-author of Programmable Logic Controller with Applications 1st edition, separately
available from two separate publishers Royal and Paramount or book sellers in the market, more than 45
papers on various topics including neural networks and signal processing and TI TMS 320C6713 DSK.
.

Muhammad Usman Sardar is a IEEE fellow from 2009. He has received his B.Sc. Electrical Engineering
degree (Hons.) from The Islamia University of Bahawalpur, Punjab, Pakistan in 2012 and studying M.Sc.
Engineering in major of Electrical Power Engineering from the same Institute. Currently he is working as
Lab Engineer in Electrical Power Engineering department of Swedish College of Engineering &
Technology, Rahim Yar Khan, Punjab, Pakistan. His areas of research interest are power transmission,
Power system protection and Electrical Machines.

Email: skhpnec@gmail.com
Email: usman_s98@yahoo.com

6
Signal and Systems
Table of contents Signature/Date
1. Introduction to MATLAB Software …………………….
1.1 Getting started with Matlab
1.2 Introduction and basic commands
1.3 Matrices
1.4 Matrix and Array Operations
1.5 MATLAB Built-in Functions
1.6 Scalar, Vector and Matrix Functions
1.7 Colon Operator and Sub-matrices
1.8 Plotting and Graphics

2. Elementary Signals and Basic Signal Operations ………


2.1 Theory of signals
2.2 Generating Discrete-Time (DT) Sequences
2.3 Generating Unit step Signal
2.4 Generating Sinusoidal Signal
2.5 Amplitude Scaling
2.6 Addition of Signals
2.7 Multiplication of two signals

3. Arrays Basic Signals and Sounds signals ……………


3.1 Starting with arrays
3.2 Arrays
3.3 MATLAB function sound
3.4 Special Matrices

4. Constructing the different exponential signals and user defined functions


for operations …………………………………..…………
4.1 Construction of Exponential Signals
4.2 General Exponential Signal
4.3 User Defined Function

5. Constructing periodic signals from harmonically related sinusoidal


signals ……………………………..…………..
I. Theory of Periodic Signal
II. Constructing periodic signals from harmonically related signals in MATLAB:

7
6. Power calculations of signals ………………………………
6.1 Calculation of Signal Power
6.2 Continuous Time Case
6.3 Discrete Time Case

7. Transformation of the Independent Variable ……………………..

I. Theory of Transformations on the independent variable

8. Creating the Even and Odd Part of different continuous time and discrete
time signals ………………………………
8.1 Theoretical Background
8.2 Plot of discrete Signal
8.3 Plot of Part 2
8.4 Plot of Part 3

9. Calculation of Fourier series of Different Function ……………………….


9.1 FOURIER SERIES
9.2 Plot of Given Signal and Its Fourier series:
9.3 MatLab Coding of Its F.S

10. To perform Convolution ……………………………………………


10.1 Theory of Convolution
10.2 Convolution in MATLAB
10.3 Inverse Fourier functions

11.Studying the Laplace and Fourier Transform and its inverse functions
practically
11.1 TRANSFORMATION ANALYSIS IN MATLAB
11.2 MATLAB CODES TO CALCULATE of FOURIER OF FUNCTION
11.3 Inverse Fourier functions
11.4 MATLAB CODES TO CALCULATE THE LAPLACE OF FUNCTION
11.5 Transform Table:

8
12. Z–transform and Z–transform analysis of signals and systems
…………………………..
12.1 Z-Transform
12.2 Theorems and Properties of Z transform
12.3 Bilateral Z-transform
12.4 Unilateral Z-transform
12.5 MATLAB Code

13. Pole zero diagram and z-transform analysis ....................................


13.1 Z-plane
13.2 Pole-Zero Diagram
13.3 ZT Analysis of DT Signals and systems

14. Discrete time Fourier transform (DTFT) …………………………...

14.1 Fourier and inverse Fourier Transform


14.2 Discrete-Time Fourier Transform
14.3 DTFT of a Rectangular pulse or Window

15.Discrete Fourier transform (DFT) and Inverse time Fourier transform


15.1 Discrete Fourier transform (DFT) and Inverse time Fourier transform
15.2 Discrete Fourier Transform
15.3 Inverse-DFT

16. Simulink and its Operation


16.1 Description
16.2 Application Toolboxes
16.3 Blocksets
16.4 The Fixed-Point Blockset
16.5 Creating a New Model
16.6 Simulink Windows
16.7 Status Bar
16.8 15.7.1 Zooming Block Diagrams
16.9 Selecting Objects
16.10 Blocks
16.11 Copying and Moving Blocks from One Window to Another
16.12 Moving Blocks in a Model
16.13 Duplicating Blocks in a Model
16.14 Specifying Block Parameters
16.15 Block Properties Dialog Box
16.16 Description
16.17 16.18 Changing the Orientation of Blocks
16.18 Resizing Blocks
16.19 Manipulating Block Names
16.20 Position of Block Names
16.21 Disconnecting Blocks

9
16.22 Building a Simple Model
16.23 Creating Subsystems
16.24 Creating a Subsystem by Adding the Subsystem Block
16.25 Creating a Subsystem by Grouping Existing Blocks
16.26 Labelling Subsystem Ports

10
Bibliography

We have consulted the following matrials/books in preparation our workbook on this subject; we must
thank and mention these books and CDs which material we found suitable of clear understanding are used
here.

Mastering Matlab 8.3 1st Ed 2005 LPE Pearson Education


by Duane Hanselman & Bruce Littlefield

Digital Signal Processing


` Laboratory using Matlab Int‟l Ed 2000
by Sanjit Mitra

11
Lab 01

Introduction to MATLAB

1.1 Getting started with Matlab


MATLAB stands for "MATrixLABoratory" which is an interactive, matrix-based computer
program for scientific and engineering numeric computation and visualization.

 Matlab is an interactive system for doing numerical computations.


 A numerical analyst called Cleve Moler wrote the first version of Matlab in the 1970s. It
has since evolved into a successful commercial software package.
 Matlab relieves you of a lot of the mundane tasks associated with solving problems
numerically.
 This allows you to spend more time thinking, and encourages you to experiment.
 Matlab makes use of highly respected algorithms and hence you can be confident about
your results.
 Powerful operations can be performed using just one or two commands.
 You can build up your own set of functions for a particular application.
 Excellent graphics facilities are available, and the pictures can be inserted into LATEX and
Word documents.

1.2 Introduction and basic commands

The aim of MATLAB is to enable us to solve complex numerical problems, without having to
write programs in traditional languages like C and FORTRAN. Thus, MATLAB interprets
commands like Basic does, instead of compiling source code like C and FORTRAN require. By
using the relatively simple programming capability of MATLAB, it is very easy to create new
commands and functions in MATLAB. In addition, these developed MATLAB programs (or
scripts) can run without modification on different computers with MATLAB. Today, MATLAB
has evolved into a very powerful programming environment by providing numerous toolboxes
such as signal processing, image processing, and control, optimization, and statistics computations.
The emphasis of this beginner's guide is on the basic MATLAB commands with investigation on
some aspects of signal processing.
1.3 Matrices
MATLAB has only one data type: a complex-valued floating-point matrix. A vector is simply a
matrix with either one row [a row vector] or one column [a column vector]. A number, or scalar, is
simply 1-by-1 matrix. Variables in MATLAB must start with an alphabetic character, and must
contain only alphabetic characters, numeric characters, and the underscore character, e.g. data is
okay, but Data!is not.

MATLAB is also case sensitive, e.g. data and Data are not the same identifier.
For example, enter the following vectors and matrix in MATLAB as
>>rowvector = [1 2 3]
rowvector =
1 2 3

12
>>columnvector = [1; 2; 3]
columnvector =
1
2
3
>> matrix2x2 = [1 2; 3 4]
matrix2x2 =
1 2
3 4
>> 4==4
ans =
1
>>
In the matrix addressing and subscripting, MATLAB is similar enough to C to cause some
extremely annoying errors. One such error is that array and vector indexing begins with 1 and
not 0.
>> x = [1 3 5 7 9]
x =
1 3 5 7 9
>>x(0)
??? Index exceeds matrix dimensions.
>>x(1)
ans =
1
For example, a 3-by-3 matrix A is defined as
>> A = [1,2,3; 4,5,6; 7 8 9]
A =
1 2 3
4 5 6
7 8 9
The element in the i'th row and j'th column of A is referred to in the usual way:
>>A(2,3)
ans =
6
In this example the expression was not explicitly assigned to a variable so MATLAB
automatically assigned the result to the variable ans. It's very easy to modify matrices:
>>A(3,2) = 10
A =
1 2 3
3 5 6
7 10 9

1.4 Matrix and Array Operations

MATLAB supports the following matrix arithmetic operations:

13
+ addition - subtraction
* multiplication ^ power
\ left division / right division
' transpose

To experience the matrix arithmetic in the MATLAB, enter the following A and b matrices
>> A = [1 2 3 ; 4 5 6 ; 7 8 10], b = [2; 4; 6]
The transpose of a matrix is the result of interchanging rows and columns. MATLAB denotes
the
[Conjugate] transpose by following the matrix with the single-quote [apostrophe].
>> B = A'
B =
1 4 7
2 5 8
3 6 9
Scalars multiply matrices as expected, and matrices may be added in the usual way; both are
done"Element by element."
>> 2*A
ans =
2 4 6
8 10 12
14 16 18

Also try the following two commands:


>> A/3
>> A + [b,b,b]
Scalars added to matrices produce a "strange" result, but one that is sometimes useful; the
scalar is added to every element.
>> A+1
ans =
2 3 4
5 6 7
8 9 10
Matrix multiplication requires that the sizes match. If they don't, an error message is
generated.
>> A*b
>>b'*A
>> A*A', A'*A
>>b'*b, b*b'

To perform point-wise operation (array operation) on matrices, we can use the "point-star"
operator, e.g. A.*B. In general, where "point" is used with another arithmetic operator it
modifies that operator's usual matrix definition to a point-wise one. Thus we have ./and .^ for
point-wise division and exponentiation.

14
Try the following commands to gain more experience on point-wise operations.
>> A^2, A.^2
>> A.*A, b.*b
>> 1./A
>> 1./A.^2

1.5 MATLAB Built-in Functions

MATLAB has a number of matrix building functions such as:


eye Identity matrix
zeros Matrix of zeros
ones Matrix of ones

For example, zeros(m,n) produces an m-by-n matrix of zeros and zeros(n) produces an
nxnzero matrix. In addition, if A is a m-by-n matrix, then zeros(A) produces a matrix of
zeros
of the same size as A. In our example A is 3-by-3 matrix, so
>>zeros(A)
ans =
0 0 0
0 0 0
0 0 0
If b is a vector, diag(b) is the diagonal matrix with b down the diagonal; if A is a square
matrix,then diag(A) is a vector consisting of the diagonal of A.
Matrices can be built from blocks. For example, if A is a 3-by-3 matrix, then
B = [A, zeros(3,2); zeros(2,3), eye(2)]will build a certain 5-by-5 matrix.

1.6 Scalar, Vector and Matrix Functions

MATLAB has some functions operate essentially on scalars while operate element-by-
element whenapplied to a matrix. The most common scalar functions are
sin cos tan
asin acos atan
exp sign rem (remainder)
abs sqrt log (natural log)
round floor ceil
Another useful MATLAB functions are vector-oriented which operate on vectors (row or
column matrices). If they are applied to a matrix, they are computed on a column-by-column
basis.

1.7 Colon Operator and Sub-matrices


The colon operator is very useful for creating index arrays, creating vectors of evenly spaced
values, and accessing submatrices.

15
The colon notation works from the idea that an index range can be generated by giving a
start,step, and then the end. Therefore, a regularly spaced vector of integers is obtained via
iii = start:step:end
Without the step parameter, the increment is 1. This sort of counting is similar to the
notationused in FORTRAN DO loops.
For example, the expression 1:6 is actually a row vector [1 2 3 4 5 6]. Try
>> 1:6
ans =
1 2 3 4 5 6
The numbers need not be integers. For example,
>> 0.1:0.2:0.9
ans =
0.1000 0.3000 0.5000 0.7000 0.9000
Also try
>> 6:-1:1
ans =
6 5 4 3 2 1
- 8 -
The following statements will, for example, generate a sinusoidal wave vector y. Try it.
x = [0.0:0.1:2.0]';

1.8 Plotting and Graphics

MATLAB is capable of producing 2-D and 3-D plots, displaying images, and even creating
and playing movies. The two most common plotting functions that will be used in the Digital
Signal Processing are plot and stem. The basic forms of plot and stem are the same with
plot(x,y) producing a connected plot with data points {{x(1),y(1)}, {x(2),y(2)},...,
{x(N),y(N)}} and stem producing a "lollipop" presentation of the same data.

Multiple plots per page can be done with the subpl


figurewindow, use subplot(3,2, title_number). For example, subplot(3,2,3) will direct the
next plot to the third tile which is in the second row, left side. For example, the above two
figurescan be put together in one page using the following commands:
>>subplot(2,1,1); plot(tt,xx);
>>subplot(2,1,2); stem(tt,xx);
In addition, the command grid will place grid lines on the current graph. The graphs can
begiven title, axes labeled, and text placed within the graph with the following commands
which take a string as an argument.
Title (graph title)
Xlabel (x-axis label)
ylabel (y-axis label)

16
Lab 2
Elementary Signals and Basic Signal Operations

2.1 Theory of signals

Unit Step Signal

The unit step signal in discrete-time is defined as:


0, n  0
u[n]  
1, n  0

Unit Impulse Signal

The unit impulse signal in discrete-time is given as:


1, n  0
 ( n)  
0, n  0

Sinusoidal Signal

The sinusoidal signal in discrete-time is given by the formula:


x[n]  A cos(0n  )
where A is the amplitude. If n is taken to be dimensionless, then both 0 and  have units of
radians.

Amplitude Scaling

Let x[n] denotes a discrete-time signal. Then the signal y[n] resulting from amplitude scaling
applied to x[n] is given by:
y[n]  cx[n]
where c is the scaling factor. In other words, the value of y[n] is obtained by multiplying the
corresponding value of x[n] by a scalar c for each sample n of the signal.

Signal Addition

Let x1[n] and x2 [n] denote a pair of discrete-time signals, then the signal y[n] obtained by the addition of
x1[n] and x2 [n] is defined by:
y[n]  x1[n]  x2 [n]

Signal Multiplication

Let x1[n] and x2 [n] denote a pair of discrete-time signals, then the signal y[n] obtained by the addition of
x1[n] and x2 [n] is defined by:
y[n]  x1[n]x2 [n]

17
This means that for each n¸ the value of y[n] is given by the product of the corresponding values of
x1[n] and x2 [n] .

2.2 Generating Discrete-Time (DT) Sequences using MATLAB


Type the following code in the MATLAB m file editor and run the program.

%% Unit Impulse
%%
close all;
clear all;
clc;
N=10; % Declaring the domain of the signal
n=[-N:1:N]; % Signal indexing vector
impulse=zeros(1,length(n)); %generates zeros from 1 till length of n
impulse(find(n==0))=1; % plot 1 at n=0
subplot(211)
stem(n,impulse); % plot discrete values of n versus values of impulse
axis([-N N -2 2]); % indicating limits of x-axis and y-axis
grid on
xlabel('Time-Index');
ylabel('Amplitude');
title('Unit Impulse');
subplot(212)

N=10;
n=[-N:0.01:N]; % Signal indexing vector
impulse=zeros(1,length(n));
impulse(find(n==0))=1; % plot 1 at n=0
impulse(find(n==0.01))=0.00
plot(n,impulse);
axis([-N N -2 2]); % indicating limits of x-axis and y-axis
grid on
xlabel('Time-Index');
ylabel('Amplitude');
title('Unit Impulse');

18
Unit Impulse
2

1
Amplitude
0

-1

-2
-10 -8 -6 -4 -2 0 2 4 6 8 10
Time-Index
Unit Impulse
2

1
Amplitude

-1

-2
-10 -8 -6 -4 -2 0 2 4 6 8 10
Time-Index

Fig. Output Waveform

2.3 Generating Unit step Signal


clf
N=10; % Declaring the domain of the signal
n=[-N:1:N]; % Signal indexing vector

step=zeros(1,length(n)); %generates zeros from 1 till length of n


step(n>=0)=1; % plot ones at all positive values
subplot(211)
stem(n,step); % plot discrete values of n versus values of stem
axis([-N N -2 2]); %indicating limits of x-axis and y-axis
grid on
xlabel('Time-Index');
ylabel('Amplitude');
title('Unit Step');
subplot(212)
n=0:0.01:N;
dstep=linspace(1,1,length(n)); %generates zeros from 1 till length of
n
plot(0,0,n,dstep)
axis([-N N -2 2]);

19
Unit Step
2

1
Amplitude

-1

-2
-10 -8 -6 -4 -2 0 2 4 6 8 10
Time-Index

-1

-2
-10 -8 -6 -4 -2 0 2 4 6 8 10

Fig. Plot of Unit Step Signal

2.4 Generating Sinusoidal Signal


clc
N=10; % Declaring the domain of the signal
n=[-N:1:N]; % Signal indexing vector
cosino=cos(n); % returns cosine for each element of n
subplot(211),stem(n,cosino); % plot discrete values of n versus
values of cosino
axis([-N N -1 1]); %indicating limits of x-axis and y-axis
grid on
xlabel('Time-Index');
ylabel('Amplitude');
title('Cosine function');
n=[-N:0.01:N]
subplot(212), plot(n,cos(n));

20
Cosine function
1

0.5
Amplitude

-0.5

-1
-10 -8 -6 -4 -2 0 2 4 6 8 10
Time-Index

0.5

-0.5

-1
-10 -8 -6 -4 -2 0 2 4 6 8 10

Fig: Plot of Sinusoidal Signal

2.5 Amplitude Scaling


impulse2=0.5*impulse; % scaling previous impulse value
figure;
subplot(1,3,1);
stem(n,impulse); % plot discrete values of n versus values of impulse
axis([-N N -2 2]); %indicating limits of x-axis and y-axis
xlabel('Time-Index');
ylabel('Amplitude');
title('Impulse');
gridon
subplot(1,3,2);
stem(n,impulse2); % plot discrete values of n versus values of
impulse2
axis([-N N -2 2]); %indicating limits of x-axis and y-axis
xlabel('Time-Index');
ylabel('Amplitude');
title('0.5*Impulse');
gridon
impulse3=-2*impulse; % scaling previous impulse values on negative
axis
subplot(1,3,3);

21
stem(n,impulse3); % plot discrete values of n versus values of
impulse3

axis([-N N -2 2]); %indicating limits of x-axis and y-axis


xlabel('Time-Index');
ylabel('Amplitude');
title('-2*Impulse');
grid on

2.6 Addition of Signals

zn=step+cosino; % adding values of step and cosine as calculated


before
figure;
subplot(1,3,1);
stem(n,step); % plot discrete values of n versus values of step
axis([-N N -2 2]); %indicating limits of x-axis and y-axis
gridon
xlabel('Time-Index');
ylabel('Amplitude');
title('Signal 1');
subplot(1,3,2);
stem(n,cosino); % plot discrete values of n versus values of cosino
axis([-N N -2 2]); %indicating limits of x-axis and y-axis
gridon
xlabel('Time-Index');
ylabel('Amplitude');
title('Signal 2');
subplot(1,3,3);
stem(n,zn); % plot discrete values of n versus values of zn
axis([-N N -2 2]); %indicating limits of x-axis and y-axis
gridon
xlabel('Time-Index');
ylabel('Amplitude');
title('Sum');

z2n=expo+cosino; % addition of expo and cosino values


figure;
subplot(1,3,1);
stem(n,expo); % plot discrete values of n versus values of expo
axis([-N N -max(z2n) max(z2n)]); %indicating limits of x-axis and y-
axis
gridon
xlabel('Time-Index');

22
ylabel('Amplitude');
title('Signal 1');
subplot(1,3,2);
stem(n,cosino); % plot discrete values of n versus values of cosino
axis([-N N -max(z2n) max(z2n)]); %indicating limits of x-axis and y-
axis
gridon
xlabel('Time-Index');
ylabel('Amplitude');
title('Signal 2');
subplot(1,3,3);
stem(n,z2n); % plot discrete values of n versus values of z2n
axis([-N N -max(z2n) max(z2n)]); %indicating limits of x-axis and y-
axis
gridon
xlabel('Time-Index');
ylabel('Amplitude');
title('Sum');

2.7 Multiplication of two signals

pn=(expo).*step;
figure;
subplot(1,3,1);
stem(n,expo); % plot discrete values of n versus values of expo
axis([-N N 0 max(expo)]); %indicating limits of x-axis and y-axis
gridon
xlabel('Time-Index');
ylabel('Amplitude');
title('Signal 1');
subplot(1,3,2);
stem(n,step); % plot discrete values of n versus values of step
axis([-N N 0 max(expo)]); %indicating limits of x-axis and y-axis
gridon
xlabel('Time-Index');
ylabel('Amplitude');
title('Signal 2');
subplot(1,3,3);
stem(n,pn); plot discrete values of n versus values of pn
axis([-N N 0 max(expo)]); %indicating limits of x-axis and y-axis
gridon

23
xlabel('Time-Index');
ylabel('Amplitude');
title('Product');

24
Lab 3
Arrays Basic Signals and Sounds signals

3.1 Starting with arrays


Matlab provides an online help system accessible by using the help command. For example
to get information size enter the following

>>help size
There is help desk desk with useful introductory material. it is accessed from the HEPL
menu. Now hare are exercise for the “Arrays”

3.2 Arrays
A variable in Matlab is an array. An array has dimension N M, where N and M are in
naturals.
N= no. of rows, M=no. of columns
If M=N=1 then variable is scalar, and if N=1 and M>1 the variable is the row vector, if N.1
and m=1 then variable is the column vector, if both M and N are greater than one, then
variable is a matrix, and if M=N >1 then it‟s a square matrix. The coefficients of the matrix
may b real or complex numbers.
Following are the example to create the arrays.

>> Array_1=[1 2 3 4 5 6]

Array_1 =

1 2 3 4 5 6

>> array_2=[ 1 2 3; 4 5 6; 7 8 9]

array_2 =

1 2 3
4 5 6
7 8 9

>> array_3=[ 1; 2; 3; 4]

array_3 =
1
2
3
4
Noe we will create the array by using the step size

25
>> v = [ 1 3, sqrt(5)]
v =
1.0000 3.0000 2.2361
>> length(v)
ans =
3
Spaces can be vitally important:
>> v2 = [3+ 4 5]
v2 =
7 5
>> v3 = [3 +4 5]
v3 =
3 4 5
>> array_3=0:5

array_3 =

0 1 2 3 4 5

>> start=0;
>> step=0.25;
>> stop=4;
>> array_4=start:step:stop
MATLAB will return us
array_4 =
Columns 1 through 7
0 0.2500 0.5000 0.7500 1.0000 1.2500
1.5000
Columns 8 through 14
1.7500 2.0000 2.2500 2.5000 2.7500 3.0000
3.2500
Columns 15 through 17
3.5000 3.7500 4.0000

We can sum up the entire array by using the command

>> sum_4=sum(array_4)
sum_4 =
34

Any built-in function that that operates on scalar can also operate on arrays. For example

>>sin (pi/4)

26
Ans=
0.7071
>>sin ([0 pi/4 pi/2 3*pi/4 pi])

Ans=
0 0.707 1.00 0.7071

This feature is called factorization. A discrete- time signal may be approximated in Matlab.
We will built a few such vectors and plot.

>> u=zeros(1,10) % this is row vector

u =

0 0 0 0 0 0 0 0 0 0

>> u(5)=1 % this will assign the value =1 to the 5th


element

>> stem(u) %plot for discrete times

Figure 4.01 stem of given discrete signal

Now we will sketch the sine wave x:[-1, 1]…reals, given by

t, x(t)= sine(2π 5t + )
MATLAB CODE
>> t=-1:.0005:1;
>> x_t=sin(2* pi* 5.*t +pi/6);
>> plot(t,x_t,'b--')

27
>>

Figure 4.02 plot of given signal

3.3 MATLAB function sound


Syntax
>>sound (sampledSignal, frequency
Sends the one dimension array or vector sampledSignal to the audio card im the pc.the 2nd
argument specifies the sampling frequency in Hz. The value in the sampledSignal are
assumed to be real no in the range [-1.00 100]. Values out side this range are clipped to -1 to
1. We will use this function to listen the signal.

>> sound( x_t, 2)


>> sound(2* x_t, 5)

>> t=0:0.005:1;
>> f_t=exp(-5.*t).*sin(2*pi*440*t);
>> plot(f_t)
>> plot(t,f_t)

>> sound(f_t, 8000)

3.4 Special Matrices


Matlab provides a number of useful built-in matrices
of any desired size.
ones(m,n) gives an m * n matrix of 1's,
>> P = ones(2,3)
P =
1 1 1
1 1 1

28
Lab 04
Constructing the different exponential signals and User Defined functions

4.1 Construction of Exponential Signals


There are different exponential signals, some of them are followings

1. Real Exponential Signal x(t)=

A discrete-time real exponential signal is expressed as


x1(t)=
where A is the amplitude of the signal at n  0 and a is a real number. For   1 , the signal
decays while for   1 , the signal grows exponentially.

1. Periodic Exponential Signal

( ) ; j is complex operator

2. Harmonic Exponential Signals


x(t)= , n is order of harmonic
3. General Exponential Signals

( )
x(t)=

4.2 General Exponential Signal

PART 1 : Real Exponential Signal


clear all
clc
clf
A=4;
a1=0.1;a2=0.2;a3=-0.1;a4=-0.2
wo=2;
t=-3:0.01:3;
x1=A*exp(a1*wo*t);
x2=A*exp(a2*wo*t);
x3=A*exp(a3*wo*t);
x4=A*exp(a4*wo*t);
plot(t,x1,'r-',t,x2,'k--',t,x3,'g:',t,x4,'b+');
legend('a1=0.1','a2=0.2','a3=-0.1','a4=-0.2');

29
Fig: General exponential signal
%% Real exponential (Decaying)

A=1; % assigning a constant value


alpha=-0.1;
expo=A*exp(alpha*n); % returns the exponential for each
element of n
figure;
stem(n,expo); % plot discrete values of n versus values of
expo
axis([-N N 0 max(expo)]); %indicating limits of x-axis and y-
axis
gridon
xlabel('Time-Index');
ylabel('Amplitude');
title('Decaying Exponential');

30
Fig: Plot of Exponential Signals

%% Real exponential (Growing)


A=1;
alpha=2;
expo2=A*exp(alpha*t); %returns the exponential for each
element of t
figure;
plot(t,expo2);
axis([-T T 0 max(expo2)]); %indicating limits of x-axis and y-
axis
gridon
xlabel('Time');
ylabel('Amplitude');
title('Growing Exponential');

PART 2 : Periodic Exponential Signal

A=5;
wo=1.5;
t=-6*pi:0.01:6*pi;
x=A*exp(j*wo*t);
plot(t,real(x),'b',t,imag(x),'g');
legend('Real part','imaginary part');

31
Fig: Periodic exponential signal

PART 3 : Harmonic Exponential Signal

A=5;
wo=2;
t=-3:0.01:3;
x1=A*exp(j*wo*t);
x2=A*exp(j*2*wo*t);
x3=A*exp(j*3*wo*t);
subplot(211);
plot(t,real(x1),'r-',t,real(x2),'g--',t,real(x3),'k.');
legend('Real part(x1)','Real part(x2)','Real part(x3)');
subplot(212);
plot(t,imag(x1),'r-',t,imag(x2),'g--',t,imag(x3),'k.');
legend('Imaginary part(x1)','Imaginary part(x2)','Imaginary
part(x3)');

32
Fig: Harmonic exponential signals

PART 4 : General Exponential Signal


A=5; wo=2;
a=-0.01;
t=-10:0.01:10;
x=A*exp((a+j*wo)*t);
plot(t,real(x),'r-',t,imag(x),'k--');
legend('Real part(x)','Imaginary part(x)');

Fig: General exponential signal


4.3 User Defined Function
Now we will draw the user defined function. i.e if we are to draw the exponential function
x(t) = for a and inputs for t.

MATLABB CODE
a=input('enter the a = ');
33
b=input('enter the phi = ');

T_min=input(' Enter the starting time = ');


T_ss=input(' Enter the Step Size on time interval = ');
T_max=input(' Enter the ending time = ');
t=T_min:T_ss:T_max;
>> title('Graph of complex exponential)')
>> xlabel('x axis')
>> ylabel('y-axis')

x_t= exp(-a.*t + i*b.*t);


plot(t,x_t)

Fig: Plot for a given values of A and

34
Lab 05
Constructing periodic signals from harmonically related sinusoidal signals

5.1 Theory of Periodic Signal

A signal is periodic if, for some positive value of T, x(t  T )  x(t ) for all t. The fundamental
period of x(t ) is the minimum positive nonzero value of t for which the above equation is
satisfied.

The sinusoidal signal x(t )  A cos(0t   ) and the complex exponential signal Ae j ( t  ) are 0

both periodic with fundamental frequency 0 and fundamental period T  2 / 0 . Associated


with the complex exponential signal is the set of harmonically related complex exponentials
given as:
k (t )  e jk0t  e jk (2 / T )t , k  0, 1  2,...

A linear combination of harmonically related complex exponentials of the form


 
x(t )  ae
k 
k
jk0t
  ak e jk0 (2 / T )t
k 

is also periodic with period T. In the above equation, the term for k = 0 is a constant, while
the terms for both k = 1 and k = -1have fundamental frequency equal to 0 and are referred
to as fundamental components or the first harmonic components. In general, the components
for k = N and k = -N are called Nth harmonic components.

5.2 Constructing periodic signals from harmonically related signals in MATLAB:


3
Let x(t )  a e
k 3
k
jk 2 t

where a0  1 , a1  a1  1/ 4 , a2  a2  1/ 2 , a3  a3  1/ 3 .


The above equation can be re-written by collecting the harmonic components with same
fundamental frequencies as follows:
x(t )  1 
4

1 j 2 t
e  e  j 2 t    e j 4 t  e  j 4 t    e j 6 t  e  j 6 t 
1
2
1
3
Using Euler‟s theorem:
1 2
x(t )  1  cos 2 t  cos 4 t  cos6 t
2 3
Close all % all figure will be cleared
Clear all % all variables will be cleared
Clc % clear code on workspace
t=[-5:0.01:5]; % time indexing vector h0=1
h1=0.5*cos(2*pi*t); % returns the cosine value for all values
of t
h2=cos(4*pi*t);
h3=2/3*cos(6*pi*t);
35
figure;
subplot(2,2,1);
plot(t,h0);
xlabel('Time');
ylabel('h0');
subplot(2,2,2);
plot(t,h0+h1);
xlabel('Time');
ylabel('h0+h1');
subplot(2,2,3);
plot(t,h0+h1+h2);
xlabel('Time');
ylabel('h0+h1+h2');
subplot(2,2,4);
plot(t,h0+h1+h2+h3);
xlabel('Time');
ylabel('h0+h1+h2+h3');

Exercise:
Solve the following Sum

∑ ( )

MATLAB CODE:
close all
clear all
clc
y=0;
for n=1:11;
y=y+cos(n);
end;
y

36
Lab 6
Calculation of Signal Power

6.1 Calculation of Signal Power


We will see how to calculate average of power of continuous and discrete time periodic
signals. Let us remember again that we can only simulate continuous time case in a digital
environment like Matlab.

6.2 Continuous Time Case


Here, we will simulate or generate one period of a continuous time cosine and calculate its
average power by using the formula

We first generate a fine time axis extending from –1 to 0.995 as follows.

>> t=-1:0.005:0.995;

We selected the period T to be 2 and to cover one period exactly, we selected the upper limit
of our time interval as 0.995.
Now, we form our cosine signal and plot it.

>> xt=cos(2*pi*t/2);
>> plot(t,xt)

We then element-wise square xt and take the absolute value.

>> abs_xt_2=abs(xt.^2);

Note the use of dot (.) operator above. When it encounters a multiplication, division or power
operation, Matlab normally tries to do the corresponding matrix operations but we can
override this and make those operations element-wise by putting a dot in front of them.

For a real signal, after squaring taking the absolute value does not make sense or is not
necessary but for a complex signal this step is necessary as dictated by the formula above.
We also note that the order of squaring and absolute value operations can be reversed or
changed. Therefore, what we did by
MCL 4 can also be accomplished by the following line.

>> abs_xt_2=abs(xt).^2;

Now, we will use Euler‟s approximation to carry out the integral. This formula simply tells
that we can approximate a definite integral using a sum.

37
In this technique, we divide the region over which we will do the integral into N parts or
t, and assume that our function stays constant over those short
intervals. Approximating a function in this (staircase) manner is depicted in Figure below. As
we increase the number of intervals N, the approximation gets better.

Figure:- Euler‟s approximation.


Approximating integrals using sums as we did above, is a deep subject of numerical analysis
or methods by itself, therefore we will not get into more detail here. It suffices for us to know
that Euler‟s formula or technique is easy to implement and produces good results for almost
all the signals that we will deal
with, as long as N is selected large enough.
Back to our main subject, to approximate or compute the average power of our cosine signal,
t as 0.005. (Can you tell where we did this? .Let
us now define this parameter and the period T .
>> delta_t=0.005; T=2;
t/T.
>> pxt=sum(abs_xt_2)*delta_t/T
pxt =
0.5000
6.3 Discrete Time Case
We will now generate one period of a discrete time cosine and calculate
its average power using the following formula

We create a vector of indices first and form our discrete time cosine signal as follows.
>> n=0:19;
>> xn=cos(2*pi*n/20);
>> stem(n,xn)
To cover exactly one period of the cosine we let the index run from 0 to 19, as the period N is
20.
The formula above to be implemented is already a sum and the calculation of average power
is really easy this time, as we are not dealing with an integral.

38
>> N=20; abs_xn_2=abs(xn.^2);
>> pxn=sum(abs_xn_2)/N
pxn =
0.5000

39
Lab 7
Transformations of the Independent variable

7.1 Theory of Transformations on the independent variable


In order to see the effects of transformations on the independent variable, we will first
generate a test signal that we will play with. Our test signal will be as shown in Figure 3.1 (or
Figure 3.2). As our signal has different linear segments, we can generate those parts one by
one and then combine them to obtain the whole signal.
We will generate the segments of time axis first and then use linspace1 commands to create
the corresponding signal segments. Linspace command is useful generating linearly changing
or equally spaced points between two limits. The two limits can be the same, in which case
the linspace command produces vectors filled with that same limit or constant.
The 1st segment of the signal goes from t =-2 to 0.

>> t1=-2:0.05:0; MCL 1


We have just generated a time vector of length 41. Now, we will create the corresponding
signal segment.

>> x1=linspace(0,0,41); MCL 2

It is better to use Matlab‟s capabilities wherever possible. One little service that we can get
from Matlab is to ask for the length of vectors via the length command. If we utilize this at
MCL 2, it would be as follows.

>> x1=linspace(0,0,length(t1));

Instead of using MCL 2, we could have also generated x1, the 1st signal segment, by the
following method that utilizes Matlab‟s zeros2 utility.

» x1=zeros(1,length(t1));

We can now generate the other segments in a similar way.


>> t2=0.05:0.05:1; MCL 3
>> x2=linspace(1,1,length(t2)); MCL 4
>> t3=1.05:0.05:2; MCL 5
>> x3=linspace(1,0,length(t3)); MCL 6
>> t4=2.05:0.05:3; MCL 7
>> x4=linspace(0,0,length(t4)); MCL 8
Note how we selected the limits of consecutive time segments above.
We can now combine both time and signal segments into single vectors and do a plot of our
signal.

>> t=[t1 t2 t3 t4]; MCL 9


>> x=[x1 x2 x3 x4]; MCL 10
>> plot(t,x); MCL 11
40
We observe in Figure 1 that Matlab‟s automatic axis scaling did not produce a good-looking
plot. We can override Matlab‟s default axes scales by using the axis3 command.

>> axis([-2 3 –0.5 1.5]) MCL 12


This is how we obtained Figure 2, plot of our signal with a different axis
scaling.

Figure 7.01 The test signal that will be used in transformation examples.

Figure 7.02 The test signal with better axes scaling.

We spent a big effort to create our test signal but the remaining part is relatively easy. Let us
see the effect of time shift first. For instance, let us try to find out how x(t +1) versus t will

41
look. We know that x(t +1) should look like x(t) shifted towards left by 1 unit in time. You
may think that we simply can
do this by the following line.

» plot(t+1,x)

But this is not true! Look at the result of this misleading idea at Figure 3,which we produced
by the following lines.

>> subplot(2,1,1);plot(t,x);axis([-3 4 –0.5 1.5])


MCL 13
>> subplot(2,1,2);plot(t+1,x);axis([-3 4 –0.5 1.5])
MCL 14

Figure 7.03 Plot of x(t) versus t (upper panel) and erroneous plot of x(t) versus t+1 (lower
panel).

Above, we utilized the subplot command that enabled us to divide the figure window into
several parts where we can examine different variables or plots simultaneously. To return
back to the default single axes (or plot) view on the figure window, we can either issue
subplot(1,1,1) or clf (clear figure)
commands.
Coming back to the real issue, we realize that what we did is actually the plot of x(t) versus t
+1, but we were after x(t +1) versus t. How can we accomplish this, i.e. do the plot of x(t +1)
versus t? Let y(t)=x(t+1) and
u=t+1; then

t=u−1 and y(u−1)=x(u).

42
As u is just a dummy variable, we can replace it with t and obtain

y(t−1)=x(t).

This indicates that our new function y(t)=x(t+1) takes the value x(t) at t −1.
Therefore, if we plot our original function x(t) with respect to a new time variable or vector
that we will form as t −1, we will get x(t +1) versus t. Let us realize this idea now.

>> subplot(2,1,1);plot(t,x);axis([-3 4 –0.5 1.5])


MCL 15
>> xlabel('t');ylabel('x(t)')
MCL 16
>> title('x(t) versus t')
MCL 17
>> subplot(2,1,2);plot(t-1,x);axis([-3 4 –0.5 1.5])
MCL 18
>> xlabel('t');ylabel('x(t+1)')
MCL 19
>> title('x(t+1) versus t')
MCL 20

We again used subplot commands to see the plots of x(t) and x(t +1) at the same time, i.e. in
the same figure window. The result is shown in Figure 4 and as we expected x(t +1) is same
as x(t) shifted towards left by 1 unit in time. Here, we also used xlabel and title commands to
make our plots more
informative.

43
Figure 7.04 Plot of x(t) versus t (upper panel) and x(t+1) versus t (lower panel).

Let us now make the plot of x(−2t) versus t to study the effects of time reversal and time
scaling. We expect x(−2t) to be a time reversed and compressed version of x(t) . To verify
this, let y(t)=x(−2t) and u= −2t; then
t= −u/ 2 or y(−u/2)=x(u).
We replace u by t and obtain y(−t/2)=x(t). Hence, y(t)=x(−2t) takes the value x(t) at −t / 2 . In
other words, plot of x(−2t) versus t is equivalent to the plot of x(t) versus −t / 2 . The
following lines will plot x(t) and x(−2t). The result is shown in Figure 5.

>> subplot(2,1,1);plot(t,x);axis([-3 4 –0.5 1.5])


MCL 21
>> xlabel('t');ylabel('x(t)')
MCL 22
>> title('x(t) versus t')
MCL 23
>> subplot(2,1,2);plot(-t/2,x);axis([-3 4 –0.5 1.5])
MCL 24
>> xlabel('t');ylabel('x(-2t)')
MCL 25
>> title('x(-2t) versus t')
MCL 26

Figure 7.05 Plot of x(t) versus t (upper panel) and x(–2t) versus t (lower panel).

As another exercise, let us plot x((t/3)−1) versus t. This example involves time scaling and
time shifting. We will use the same approach again, where we find the time at which the new

44
or transformed signal y(t) takes the value of the original signal x(t) . This way, we keep the
original signal the same
and plot it with respect to a transformed time variable or vector, to find the transformed
signal.

Let y(t)=x((t /3)−1) and u=(t/3)−1; then t=3(u+1) and y(3(u+1))=x(u) . We replace u by t and
obtain y(3(t+1))=x(t) . We can now complete our task by the following lines. The result is
shown in
Figure 6 and as we see x((t/3)−1) is expanded/stretched and right shifted (by 3 units in time)
version of x(t) .
>> subplot(2,1,1);plot(t,x);axis([-4 14 -0.5 1.5])
MCL 27
>> xlabel('t');ylabel('x(t)')
MCL 28
>> title('x(t) versus t')
MCL 29
>> tnew=3*(t+1);
MCL 30
>> subplot(2,1,2);plot(tnew,x);axis([-4 14 -0.5 1.5])
MCL 31
>> xlabel('t');ylabel('x((t/3)-1)')
MCL 32
>> title('x((t/3)-1) versus t')
MCL 33

Figure 7.06 Plot of x(t) versus t (upper panel) and x((t/3)−1) versus t (lower panel).

45
Lab 8
To sketch Even and Odd Part of different continuous time and discrete time signals

8.1 THEORETICAL BACKGROUND

The signal can be divided into 2 parts i.e., evenpart and odd part. They are calculated as

( ) ( )
Even part of signal x(t) =

( ) ( )
Odd part of signal x(t) =

8.2 Plot of discrete Signal

Fig:8.01 Discrete Signal

MATLAB CODE:-
n=-10:10;
xn=zeros(1,length(n));
xn(find(n==-2))=-1;
xn(find(n==0))=3;
xn(find(n==1))=2;
xn(find(n==2))=1;
xn(find(n==7))=1;
xn_f=fliplr(xn);
xne=(xn+xn_f)/2;
xno=(xn-xn_f)/2;
subplot(411);stem(n,xn);

xlabel('n');ylabel('xn');
46
axis([-10 10 -2 4]);
subplot(412);stem(n,xn_f);
xlabel('n');ylabel('xn_f');
axis([-10 10 -2 4]);
subplot(413);stem(n,xne);
xlabel('n');ylabel('xne');
axis([-10 10 -2 4]);
subplot(414);stem(n,xno);
xlabel('n');ylabel('xno');
axis([-10 10 -2 4]);
OUTPUT GRAPH

Fig:8.02 Discrete Signal, horizontal mirror,even part and odd part of the disrete signal
8.3 Plot of Part(2)
To sketch The Even And Odd Part Of The Given Signals

47
Fig:8.03 Given Continuous Signal

48
MATLAB CODE:-
t1=-10:0.01:-2;
t2=-2:0.01:-1;
t3=-1:0.01:0;
t4=0:0.01:1;
t5=1:0.01:10;

t=[t1 t2 t3 t4 t5];
x1=linspace(0,0,length(t1));
x2=linspace(0,1,length(t2));
x3=linspace(1,0,length(t3));
x4=linspace(0,1,length(t4));
x5=linspace(1,1,length(t5));
x=[x1 x2 x3 x4 x5];
xhm=fliplr(x);
xe=(x+xhm)/2;
xo=(x-xhm)/2;
subplot(411);plot(t,x);
xlabel('t');ylabel('x');

axis([-10 10 -2 4]);
grid on;
subplot(412);plot(t,xhm);
xlabel('t');ylabel('xhm');
axis([-10 10 -2 4]);
grid on;
subplot(413);plot(t,xe);
xlabel('t');ylabel('xe');
axis([-10 10 -2 4]);
grid on;
subplot(414);plot(t,xo);
xlabel('t');ylabel('xo');
axis([-10 10 -2 4]);
PLOT :-

49
Fig:8.04 Continuous Signal, horizontal mirror,even part and odd part of the Continuous
signal

8.4 Plot of Part(3)


To sketch The Even And Odd Part Of The Given
Signals

Figure: 8.05 Given Continuous Signal

MATLAB CODE:-
t1=-10:0.01:-2;
t2=-2:0.01:-1;
t3=-1:0.01:0;
50
t4=0:0.01:1;
t5=1:0.01:2;
t6=2:0.01:3;
t7=3:0.01:10;
t=[t1 t2 t3 t4 t5 t6 t7];
x1=linspace(0,0,length(t1));
x2=linspace(0,1,length(t2));
x3=linspace(1,1,length(t3));
x4=linspace(1,2,length(t4));
x5=linspace(2,2,length(t5));
x6=linspace(2,0,length(t6));

x7=linspace(0,0,length(t7));
x=[x1 x2 x3 x4 x5 x6 x7];
xhm=fliplr(x);
xe=(x+xhm)/2;
xo=(x-xhm)/2;
subplot(411);plot(t,x);
xlabel('t');ylabel('x');
axis([-10 10 -2 4]);
grid on;
subplot(412);plot(t,xhm);
xlabel('t');ylabel('xhm');
axis([-10 10 -2 4]);
grid on;
subplot(413);plot(t,xe);
xlabel('t');ylabel('xe');
axis([-10 10 -2 4]);
grid on;
subplot(414);plot(t,xo);
xlabel('t');ylabel('xo');
axis([-10 10 -2 4]);
grid on:

51
Fig: 8.06: Output graph Continuous Signal, horizontal mirror,even part and odd part of the
Continuous signal

52
Lab 9
Creating the Fourier series of a different Signals

9.1 FOURIER SERIES


In mathematics, a Fourier series decomposes any periodic function or periodic signal into the
sum of a (possibly infinite) set of simple oscillating functions, namely sines and cosines (or
complex exponentials). The study of Fourier series is a branch of Fourier analysis. Fourier
series were introduced by Joseph Fourier (1768–1830) for the purpose of solving the heat
equation in a metal plate.

Fourier series are used in the analysis of periodic functions.

Many of the phenomena studied in engineering and science are periodic in nature eg. the
current and voltage in an alternating current circuit. These periodic functions can be analysed
into their constituent components (fundamentals and harmonics) by a process called Fourier
analysis.

Figure: A periodic function

Given f(t) is periodic; f(t) can be represented as follows:


( ) ∑ ( ) ( )

Where n is the integer sequence 1,2,3, ...


a0, an , and bn are called the Fourier coefficients, and are calculated from f(t),
0 = 2 /To is the fundamental frequency

9.2 Plot of Given Signal and Its Fourier series:


( ) ;

Here T0= , 0=

( ) ∑ ( ( ) ( )) ]
MatLab Coding of Original Signal
t=0:0.001:pi;
y=1*exp(-t./2);
plot(t,y)

53
Fig: Plot of Original Signal
9.3 MatLab Coding of Its F.S
t=-3*pi:0.001:3*pi;
s1=0; s2=0;
for n=-1000:1:-1;
an=(0.504)*[2./(1+16*n.^2)];
x1=an*cos(2*n*t);
s1=s1+x1;
end;
for n=1:1:1000;
bn=(0.504)*[8*n./(1+16*n.^2)];
x2=bn*sin(2*n*t);
s2=s2+x2;
end;
x=0.504+s1+s2;
plot(t,x)

54
Figure: plot of Fourier series of given signal

55
Lab 10

To perform convolution

10.1 Theory of Convolution

Let a system is given by y[n]  f ( x[n]) , where x[n] be the input signal and y[n] be the output
signal. Let h[n] be the impulse response of the system i.e. h[n]  f ( [n]) . Then the response
y[n] of the system to any arbitrary input x[n] can be determined using the convolution sum as
follows:

y[n]  x[n]* h[n]   x[k ]h[n  k ]
k 

The convolution operation is

 Commutative, i.e. x[n]* h[n]  h[n]* x[n] ;


 Distributive i.e. x[n]*(h1[n]  h2 [n])  x[n]* h1[n]  x[n]* h2[n] ; and
 Associative i.e. x[n]*(h1[n]* h2 [n])  ( x[n]* h1[n]) * h2[n]

10.2 Convolution in MATLAB

In MATLAB, convolution of two signals can be performed by the function conv(h, x). If h is
a vector of length M and x is a vector of length N, then the length of the output vector is M +
N – 1.

h is a vector of length M
x is a vector of length N
y is a vector of length M + N - 1

Type and run the following code in MATLAB:

clear all;
close all;
clc;
h=[3 2 1 -2 1 0 -4 0 3]; % impulse response
org_h = 1; % Sample number where origin exists
nh=[0 : length(h)-1]; % indicating the length of sample
x = [1 -2 3 -4 3 2 1]; % input sequence
org_x = 1; % Sample number where origin exists
nx = [0 : length(x)-1]; % indicating the length of sample
y = conv(h,x);
ny = [nh(1)+ nx(1) : nh(end)+nx(end)]; % indicating the length
of convolved sample
figure;
subplot(3,1,1),
stem(nh,h);

56
xlabel('Time index n');
ylabel('Amplitude');
xlim([nh(1)-1 nh(end)+1]);
title('Impulse Response h(n)'); grid;
subplot(3,1,2),
stem(nx,x);
xlabel('Time index n'); ylabel('Amplitude');
xlim([nx(1)-1 nx(end)+1]);
title('Input Signal x(n)'); grid;
subplot(3,1,3)
stem(ny,y);
xlabel('Time index n');
ylabel('Amplitude');
xlim([ny(1)-1 ny(end)+1]);
title('Output Obtained by Convolution'); grid;

Figure; Output Graph

57
58
Lab 11
Studying Fourier and Laplace Transform and its inverse functions practically

11.1 TRANSFORMATION ANALYSIS IN MATLAB


In mathematics, the Laplace transform is a widely used integral transform. Denoted
, it is a linear operator of a function f(t) with a real argument t (t ≥ 0) that
transforms it to a function F(s) with a complex argument s. This transformation is essentially
bijective for the majority of practical uses; the respective pairs of f(t) and F(s) are matched in
tables. The Laplace transform has the useful property that many relationships and operations
over the originals f(t) correspond to simpler relationships and operations over the images
F(s).[1] The Laplace transform has many important applications throughout the sciences. It is
named for Pierre-Simon Laplace who introduced the transform in his work on probability
theory.

11.2 MATLAB CODES TO CALCULATE of FOURIER OF FUNCTION


>> syms t a; %variable initialization
>> f=t^2; % time domain
>> F=fourier(f)

>> f=1/(1+t^2) %time domain


>> Prettty(f)
>> F=fourier(f)

>> syms w;
>> F=1/(1+w^2)
>> pretty(F)
>> f=ifourier(F)

>> subplot(211)
>> ezplot(F)
>> subplot(212)
>> ezplot(f)

59
Figure: plot of given function and its inverse fourier
>> f=dirac(t);
>> F_1=fourier(f)

11.3 Inverse Fourier functions


>> syms w
>>F=2/(j*w)
F =
-2*i/w
>> f=ifourier(F)
f =
2*heaviside(x)-1
>>ezplot(f)
>> f=heaviside(t);
>> F=fourier(f)
F =
pi*dirac(w)-i/w

11.4 MATLAB CODES TO CALCULATE THE LAPLACE OF FUNCTION


>>syms t
>> f=t;
>> F=laplace(f)
F =
1/s^2
>> subplot(211)
>> ezplot(f)
>> subplot(212)
60
>> ezplot(F)

Figure
>> F_2=laplace(f)
>> f=heaviside(t);
>> F=fourier(f)
>> uu=ifourier(F) % we will get back function f
>> F=laplace(f)
>>uu2=ilaplace(F)

11.5 Transform Table:

Sr. F(t) F(jw) F(s)


No.

1 () Dirac(t) 1 1

U(t) = pi*dirac(w)-i/w 1/s


2
heaviside(t)

t U(t) = t * i*(pi*dirac(1,w)*w^2+i)/w^2 1/s^2


3
heaviside(t)

61
4 1/t i*pi*(1-2*heaviside(w)) laplace(1/t,t,s)

5 t2 U(t) -2*pi*dirac(2,w) 2/s^3

62
Lab 12
Z–transform and z t analysis of signals and systems

12.1 Z-Transform
The Z-transform of a number sequence {x(nT)} or {x(n)} is defined as the power series in z -n
(where z is a complex variable = r ejω), with coefficients equal to the sample-values of x(n),

This transform is the expressed as follows.



X(z)  z [{x(n)}]  x(n)z-n
n0

If the sequence {x(n)} is generated from a time function x(t) by sampling every T seconds,
x(n) is understood to be x(nT); that is, T is dropped for convenience. The region of
convergence (ROC) of X(z) is the set of all values of z for which X(z) attains a finite value.
Thus any time we cite a z-transform we should also indicate its ROC. Z –Transform Analysis
is an important technique in the analysis of characterization of discrete time signals and LTI
systems, e.g. by pole zero locations. Z – transform is an important tool in DSP that gives the
solution of difference equations in a single step. Since Z – Transform is an infinite power
series, it exists only for the region for which this series converges (region of convergence
ROC). Inverse Z – Transform is the method to obtain the time domain representation of a
signal, from its z-Transform.

12.2 Theorems and Properties of Z transform


i.) Addition: The z-transform of the sum of number sequences is equal to the sum of the z-
transform of the number sequence; that is
 
Z[{x1 (n)  x1 (n)}]   x1(n)z-n   x2 (n)z-n  X1 (z)  X 2 (z)
n0 n0

ii.) Scaling:
The z transform of a number sequence multiplied by constant is equal to the constant
multiplied by the z-transform of the number sequence; i.e.

 
Z[a{x(n)}]   a x(n) z n  a  x(n) z  n  a X(z)
n0 n0

iii.) Time Shifting: Let n be a +ve integer, and let x(n) be zero for n less than zero. Further
let X(z) be the z-transform of {x(n)}.

Z Z
x(n)   z k X(z) x(n  k) 
 X(z) x(n  k)  Z
 zk X(z)
iv.) Differentiation in Z-Domain

Z
x(n) 
 X(z)
Z d[X(z)]
nx(n) 
 z
dz

63
v.) Convolution of two Sequences.

Z Z
If x1(n) 
 X1(z) and x2(n) 
 X2(z)
Then
x(n)  x1(n) * x2 (n) Z X(z)  X1(z).X2 (z)

12.3 Bilateral Z-transform


The bilateral or two-sided Z-transform of a discrete-time signal x[n] is the function X(z)
defined as

12.4 Unilateral Z-transform


Alternatively, in cases where x[n] is defined only for n ≥ 0, the single-sided or unilateral Z-
transform is defined as

The z-transform is the discrete-time counter-part of the Laplace transform and a


generalization of the Fourier transform of a sampled signal. The z-transform allows insight
into the transient behavior, the steady state behavior, and the stability of discrete-time
systems. A working knowledge of the z-transform is essential to the study of digital filters
and systems.

12.5 MATLAB Code


syms z n

y=ztrans(1/4^n)

y =
4*z/ (4*z-1)
>>Pretty(y)
z
4 -------
4 z - 1
>>

Inverse Z-Transform
X(n) = Z-1 [ X(Z)]

X(Z) = 3*Z / (Z+1)

MATLAB Code
syms Z n
64
ans=iztrans(3*Z/(Z+1))

return
ans =3*(-1) ^n
>> pretty(ans)
n
3 (-1)
>>

Z – TRANSFORM

12.6 Z – Transform of a Discrete Time Function:


It is to be noted all solutions in Matlab is for causal system i.e. n>0
Let the x(n) be:
n
1
x(n)    u(n)
4
syms z n
ztrans((1/4)^n)

Result:
ans = 4*z/(4*z-1)

12.7 Inverse Z – Transform


Let the function in Z domain is:
2z
X(z) 
2z  1
syms z n
iztrans(2*z/(2*z-1))

Result:
ans = (1/2)^n

TEST YOURSELF
Q
What is the purpose of syms command ?
___________________________________________________________________________
_____________________________________________________________

Q
Find out the z – Transform of the following function, using Matlab code.
1
x(n)  2  2n u(n)  4( )n U(n)
2
Matlab code:
65
___________________________________________________________________________
_____________________________________________________________
____________________________________________________________________

Result:
___________________________________________________________________________
_____________________________________________________________

66
Q
Determine the convolution of the following pairs of signals by means of the z-transform.
1 n 1
For calculating z-transform of x1(n) we have to modify it x1(n)  ( 14 ) ( 14 ) u(n  1)
1 n
It means {x1(n)}  4z {( 14 ) u(n)

x2 (n)  [1  ( 12 )n]u(n)  [1 u(n)  ( 12 )nu(n)]

Matlab code:
___________________________________________________________________________
_____________________________________________________________
____________________________________________________________________

Result:
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
__________________

Q
Find the inverse z-transform of the following transfer function
1
Y(z) 
(1  z )(1  z 1 )2
1

Result:
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
_______________________________________________
Q
Find out the inverse z – Transform of the following function?
6  9z 1
X(z) 
1  2.5z 1  z 2
Result:
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
_______________________________________________

Q
67
Determine the Z-transform of 10 cos 2n

Result:

68
Lab 13
Pole zero diagram and z-transform analysis

13.1 Z-plane

zplane command compute and display the pole – zero diagram of z – function.
The command is
>> zplane(n,d)
To display the pole value, use root(d) command.
To display the zero value, use root(n) command.

pzmap command compute and display the pole – zero map diagram of z – function.
The command is
>> pzmap(n,d)

13.2 Pole-Zero Diagram


1  1.6180z 1  z 2
X(z) 
1  1.5161z 1  0.878z  2

n=[1 -1.6180 1]; % same as bs in Difference Eqn. model


d=[1 -1.5161 0.878]; % same as as in Difference Eqn. model
roots(d) % Poles of the function
roots(n) % Zeroes of the function
zplane(n,d) % generates pole-zero diagram of the function
pzmap(n,d)

Result:
roots (d) =
0.7581 + 0.5508i
0.7581 - 0.5508i
roots (n) =
0.8090 + 0.5878i
0.8090 - 0.5878i

z-Plane diagram Pole zero map diagram

69
Pole-Zero Diagram

13.3 zT Analysis of DT Signals and systems

Given is the system function of a DT LTI system


num = [2 4 8 5 2]; % bs
den = [2 36 3 2 1]; % as

i.) POLE-ZERO PLOT

zplane(num,den); % there are 2 real poles, 1 pair of imaginary poles and 2 pairs
of imaginary zeros

ii.) POLE-ZERO-GAIN CALCULATION

[z p k] = tf2zp(num,den) % TF2ZP Transfer function to zero-


pole conversion.
% [Z,P,K] = TF2ZP(NUM,DEN) finds the zeros, poles, and
gains
Result
z = (system zeros)
-0.6206 + 1.5168i
-0.6206 - 1.5168i
-0.3794 + 0.4779i
-0.3794 - 0.4779i

p = (system poles)
-17.9193
0.0935 + 0.3091i
0.0935 - 0.3091i
-0.2676
70
This system will NOT be stable if considered Causal, because the largest pole is outside unit-
circle.

k= 1 (system gain)

iii.) CALCULATION OF SOS (second-order sections)

SoS = zp2sos(z, p, k)

Result
SoS = 1.0000 1.2413 2.6859 1.0000 18.1869
4.7953
1.0000 0.7587 0.3723 1.0000 -0.1869
0.1043

Matlab Notes

ZP2SOS Zero-pole-gain to second-order sections model conversion.


[SOS,G] = ZP2SOS(Z,P,K) finds a matrix SOS in second-order sections form and a gain G
which represent the same system H(z) as the one with zeros in vector Z, poles in vector P and
gain in scalar K.

The poles and zeros must be in complex conjugate pairs.

G is a scalar which accounts for the overall gain of the system. If G is not specified, the gain
is embedded in the first section. The second order structure thus describes the system H(z) as:
H(z) = G*H1(z)*H2(z)*...*HL(z)

iv.) CALCULATION OF NUM AND DEN FROM POLE-ZERO-GAIN

[numA denA] = zp2tf(z,p,k)

Result
numA = 1.0000 2.0000 4.0000 2.5000 1.0000
denA = 1.0000 18.0000 1.5000 1.0000 0.5000

v.) CALCULATION OF IMPULSE FUNCTION

figure; impz(num,den,500) % or fvtool(num,den)

71
vi.) PARTIAL-FRACTION EXPANSION

[R,P,K] = residuez(num,den)

Result
R = 0.9043
-0.6784 - 0.3001i
-0.6784 + 0.3001i
-0.5475
P = -17.9193
0.0935 + 0.3091i
0.0935 - 0.3091i
-0.2676
K = 2

Matlab Notes:
RESIDUEZ Z-transform partial-fraction expansion.
[R,P,K] = RESIDUEZ(B,A) finds the residues, poles and direct terms of the partial-
fraction expansion of B(z)/A(z),

B(z) r(1) r(n)


  1
 ......  k(1)  k(2)z 1......................
A(z) 1  p(1)z 1  p(n)z 1

B and A are the numerator and denominator polynomial coefficients, respectively, in


ascending powers of z-1. R and P are column vectors containing the residues and poles,
respectively. K contains the direct terms in a row vector.

vii.) Frequency Response Estimation:


The freqz function computes and display the frequency response of given z – transform of the
function.

72
Matlab notes:
freqz(n,d,npt,Fs)

%Where Fs is the sampling frequency, npt is the no. of frequency points between and
Fs/2.

1  1.6180z 1  z 2
X(z) 
1  1.5161z 1  0.878z 2

n=[1 -1.6180 1];


d=[1 -1.5161 0.878];
freqz(n,d)
Result:
10
Magnitude (dB)

-10

-20

-30
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Normalized Frequency ( rad/sample)

100
Phase (degrees)

50

-50

-100
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Normalized Frequency ( rad/sample)

Normalized Frequency Plots

viii.) Impulse Response:

Look at the following difference equation

y[n] – 1.8 cos(π/16) y[n-1] + 0.81 y[n-2] = x[n] + ½ x[n-1]

We can calculate impulse response of this system

a = [1 –1.8*cos(pi/16) 0.81];
b = [1 ½] ;
figure; impz(b,a); grid

This function can also be expanded in Partial Fractions by

[ r c l ] = residuez (b,a) ;

ix.) Pole-Zero Plot

73
figure; zplane(b,a)

As you „ll see in the pole-zero plot of this discrete-time system, the poles of this system are
inside unit circle ; hence it‟s a stable system.

You can also first calculate pole-zeros and gain of the function and then generate pole-zero
plot by typing

[ z p k ] = tf2zp (b,a) ;
figure; zplane(z,p);

74
Lab # 14
Discrete-time Fourier transforms (DTFT)

14.1 Fourier and inverse Fourier Transform


Fourier and inverse Fourier are the mathematical tools that are used to switch from time-
domain to frequency-domain and vice versa, in order to view a signal. This conversion
between time and frequency domains is very helpful in enhancing the understanding of
signals and systems. This is called Fourier analysis. There is an entire family of Fourier
analysis techniques, where each specific technique is applied to a particular type of signals -
continuous or discrete, and periodic or a periodic – In order to determine its frequency
content. These distinctions results in four categories of signals;

Continuous-time (CT) and periodic


Discrete-time (DT) and periodic
Continuous-time (CT) and aperiodic
Discrete-time (DT) and aperiodic

For a continuous time periodic signal, the Fourier analysis technique is CT Fourier series. For
continuous-time aperiodic signal, it is CT Fourier transform. In DSP, our main interest lies in
signals that are discrete in time. The transform techniques used in this case are the discrete
Fourier series (DFS) or DT Fourier series (DTFS) for discrete time periodic signals and
discrete time Fourier transform (DTFT) for discrete time aperiodic signals. The table lists the
transform that are used for different types of signals.

Continuous Discrete
Periodic CT Fourier series DT Fourier series
Aperiodic CTFT DTFT

Transforms for different signals

Continuous time or analog systems are modelled by a set of differential equations and the
transform used in the analysis of LTI analog systems is the Laplace transform, which is
strongly related with CTFT. (Laplace Transform becomes CTFT on imaginary axis in s-
plane.) Discrete time systems are modelled by a set of difference equations and the transform
used in the analysis of LTI discrete systems is the Z-transform, which is strongly related with
DTFT. (z Transform becomes DTFT on unit circle in z-plane.)

As most of the practical signals of interest are aperiodic signals, hence it is DTFT that we are
frequently coming across. DTFT is a continuous function and consequently in computer, its
discretized or sampled version is computed. This sampled version of DTFT is called Discrete
Fourier Transform (DFT).

The DFT is one of the most common and powerful algorithms of digital signal processing. It
is used in a wide variety of applications in many branches of science and engineering. For
75
example, it allows for more efficient implementation of DSP algorithms, such as those for
digital filtering, convolution and correlation.
The plot of DTFT / DFT is called frequency spectrum which basically is of two types;
i. Amplitude or Magnitude spectrum
ii. Phase spectrum

DISCRETE-TIME FOURIER TRANSFORM (DTFT)

14.2 Description:

Fourier Analysis technique for DT aperiodic functions generates Discrete-time Fourier


Transform (DTFT), just as it gives Continuous-time Fourier Transform (CTFT), for CT
aperiodic functions.

14.3 DTFT of a Rectangular pulse or Window

i.) Generating a Discrete-time Rectangular pulse of length 12

L=12;
x = ones(L,1); % You can also use commands rectwin or
boxcar
[X,w] = freqz(x,1,512) ; % Calculation of DTFT
% larger the no. of points (512), smoother the plot is
figure; subplot(211);plot(w/pi, abs(X)); grid
ylabel(‘Magnitude of DTFT’
subplot(212);plot(w/pi, angle(X)); grid
ylabel(‘Phase’)
xlabel(‘Radian frequency normalized by pi’)

76
15
Magnitude of DTFT

10

0
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

0
Phase

-1

-2

-3
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Radian frequency normalized by pi

Magnitude and Phase plots of the DTFT

TEST YOURSELF:

Q
What is the peak of the spectrum ? Why ?
___________________________________________________________________________
___________________________________________________________________________
_______________________________________

Q
Where are the zeros locations (Nulls) in the plot ? What is their significance ?
___________________________________________________________________________
___________________________________________________________________________
_______________________________________

Q
Spacing between nulls is actually equal to 2 / L. Verify this fact by changing L to 21.

77
If you change the shape of the pulse or window x, from rectangular to a smoother, triangular
one, what do you think will be the effect on its frequency spectrum (DTFT)?
___________________________________________________________________________
___________________________________________________________________________
______________________________________

Q
You can also study other famous windows, using commands blackman, hamming, hann etc.
___________________________________________________________________________
___________________________________________________________________________
______________________________________

78
LAB # 15

Discrete Fourier Transforms (DFT) And Inverse-Dft (Idft)

15.1 Description:

The general mathematical expression for N-point DFT of an input sequence x(n) is given by:
N 1
X(k)   x(n)e  j2kn / N k = 0, 1, … , N-1
n0

Similarly, by using the tool of inverse discrete Fourier transform (IDFT), a discrete-time
signal in frequency domain can be converted back to time domain. It is just the reverse
process of Discrete Fourier Transform. The general mathematical expression for IDFT having
an input sequence X(K) is given by:
N 1
x(n)  (1 / N)  X(k)e j2kn / N n = 0, 1, … , N-1
k 0

Algorithms can be developed that give the DFT or inv-DFT for an input sequence having any
number of samples (points).

The functions X = fft(x) and x = ifft(X) implement the transform and inverse transform pair
given for vectors of length by:

Where

is an Nth root of unity.


15.2 Discrete Fourier Transform

k=0:3;
x=[1 1 2 2];
X=fft(x,4);
% 4-point DFT of x
subplot(211); stem(k,abs(X));
xlabel('k'); ylabel('Amplitude'); grid;
title(‘DFT’);
subplot(212); stem(k,angle(X));
xlabel('k'); ylabel('Phase'); grid;
79
Result:

The plot of the magnitude and the phase of the DFT for the given input is shown below.
amplitude obtained by dft
6
Amplitude

0
0 0.5 1 1.5 2 2.5 3
Time index n
phase obtained by dft
4

2
phase

-2

-4
0 0.5 1 1.5 2 2.5 3
Time index n

Magnitude/ Phase plot of the DFT

15.3 Inverse-DFT
Y=[6.0000 , -1.0000 + 1.0000i , 0 , -1.0000 - 1.0000i];
y=ifft(Y,4);
n=0:3;
stem(n,y); grid
xlabel('Time index n'); title(‘inverse DFT’);

Result:
The plot of inv-DFT for the given input is shown below.

amplitude obtained by idft


2

1.8

1.6

1.4

1.2
Amplitude

0.8

0.6

0.4

0.2

0
0 0.5 1 1.5 2 2.5 3
Time index n

80
Magnitude plot of the inv-DFT

15.4 Exploration of no. of points in DFT / IDFT

x = [1 4 9 11 8 3];
X1 = fft(x,512); % 512-pt. DFT

X2 = fft(x,8); % 8-pt. DFT


Result:
36.0000 -14.0711 -17.4853i 0 + 4.0000i
0.0711 + 0.5147i
0 0.0711 - 0.5147i 0 - 4.0000i -14.0711
+17.4853i

X3 = fft(x,6); % 6-pt. DFT


Result:
36.0000 -15.0000 - 1.7321i 0 0
0 -15.0000 + 1.7321i

X4 = fft(x,4); % 4-pt. DFT


Result:
25.0000 -8.0000 + 7.0000i -5.0000 -
8.0000 - 7.0000i

ifft(X4) % 4-pt. inv-DFT


Result:
1 4 9 11

TEST YOURSELF:

What command line performs the function of IDFT in the above program?
___________________________________________________________________________
___________________________________________________________________________
______________________________________________________

What is the resulting output sequence of the IDFT operation for given complex sequence Y.
81
___________________________________________________________________________
___________________________________________________________________________
______________________________________________________

Modify the above program for the same input sequence „Y„, to calculate 8 point IDFT.
___________________________________________________________________________
___________________________________________________________________________
_____________________________________________________

82
LAB 16
Simulink and its Operation
16.1 Description
Simulink® is a software for modeling, simulating, and analyzing dynamic systems. It
supports linear and nonlinear systems, modeled in continuous time, sampled time, or a hybrid
of the two. Systems can also be multirate, i.e., have different parts that are sampled or
updated at different rates.

16.2 Application Toolboxes


Simulink users have direct access to the wide range of MATLAB-based tools for generating,
analyzing, and optimizing systems implemented in Simulink. These tools include MATLAB
Application Toolboxes, specialized collections of M-files for working on particular classes of
problems.

All toolboxes are built using MATLAB. This has some very important implications for you:
• Every toolbox builds on the robust numerics, rock-solid accuracy, and years of experience
in MATLAB.
• You get seamless and immediate integration with Simulink and any other toolboxes you
may own.
• Because all toolboxes are written in MATLAB code, you can take advantage of
MATLAB‟s open- system approach. You can inspect M-files, add to them, or use them for
templates when creating your own functions.
• Every toolbox is available on any computer platform that runs MATLAB.

The list of professional toolboxes available in Matlab can be viewed by selecting the
Contents in the Help menu.
1.3 Blocksets

Similar to MATLAB and its application toolboxes, The MathWorks offers blocksets for use
with Simulink. Blocksets are collections of Simulink blocks that are grouped in a separate
library from the main Simulink library.

16.4 The Fixed-Point Blockset

The Fixed-Point Blockset allows you to simulate fixed-point effects in a convenient and
productive environment. The blocks provided by the Fixed-Point Blockset include:

 Addition and subtraction


 Multiplication and division
 Summation
 Gains and constants
 Conversion between floating-point and fixed-point signals
 One- and two-dimensional lookup tables
 Logical operators

83
 Relational operators
 Conversion/saturation of fixed-point signals
 Switch between two values
 Delay
 Delta-inverse operator
 Monitoring signals

16.5 Starting Simulink

To start Simulink, you must first start MATLAB. You can then start Simulink in two ways:
 Click on the Simulink icon on the MATLAB toolbar
 Enter the simulink command at the MATLAB prompt

On Microsoft Windows platforms, starting Simulink displays the Simulink Library Browser.

Simulink Library Browser

The Library Browser displays a tree-structured view of the Simulink block libraries installed
on your system. You can build models by copying blocks from the Library Browser into a
model window.

The Simulink library window displays icons representing the block libraries that come with
Simulink. You can create models by copying blocks from the library into a model window.

16.6 Creating a New Model

To create a new model, click the New button on the Library Browser‟s toolbar (Windows
only) or choose New from the library window‟s File menu and select Model. You can move
the window as you do other windows.

84
16.7 Simulink Windows

Simulink uses separate windows to display a block library browser, a block library, a model,
and graphical (scope) simulation output.

16.8 Status Bar

The Windows version of Simulink displays a status bar at the bottom of each model and
library window.

16.9 Zooming Block Diagrams

Simulink allows you to enlarge or shrink the view of the block diagram in the current
Simulink window. To zoom a view:

 Select Zoom In from the View menu (or type r) to enlarge the view.
 Select Zoom Out from the View menu (or type v) to shrink the view.
 Select Fit System to View from the View menu (or press the space bar) to fit
the diagram to the view.
 Select Normal from the View menu to view the diagram at actual size.

By default, Simulink fits a block diagram to view when you open the diagram either in the
model browser‟s content pane or in a separate window. If you change a diagram‟s zoom
setting, Simulink saves the setting when you close the diagram and restores the setting the
next time you open the diagram. If you want to restore the default behavior, choose Fit
System to View from the View menu the next time you open the diagram.

16.10 Selecting Objects

Many model building actions, such as copying a block or deleting a line, require that you first
select one or more blocks and lines (objects).
16.11 Blocks

Blocks are the elements from which Simulink models are built. You can model virtually any
dynamic system by creating and interconnecting blocks in appropriate ways.

85
16.12 Copying and Moving Blocks from One Window to Another

As you build your model, you often copy blocks from Simulink block libraries or other
libraries or models into your model window. To do this, follow these steps:

 Open the appropriate block library or model window.


 Drag the block you want to copy into the target model window. To drag a block,
position the cursor over the block icon, then press and hold down the mouse button.
Move the cursor into the target window, then release the mouse button.
You can also drag blocks from the Simulink Library Browser into a model window.
You can also copy blocks by using the Copy and Paste commands from the Edit menu:

 Select the block you want to copy.


 Choose Copy from the Edit menu.
 Make the target model window the active window.
 Choose Paste from the Edit menu.

Simulink assigns a name to each copied block. If it is the first block of its type in the model,
its name is the same as its name in the source window. For example, if you copy the Gain
block from the Math library into your model window, the name of the new block is Gain. If
your model already contains a block named Gain, Simulink adds a sequence number to the
block name (for example, Gain1, Gain2).

When you copy a block, the new block inherits all the original block‟s parameter values.

Moving blocks from one window to another is similar to copying blocks, except that you hold
down the Shift key while you select the blocks.
You can use the Undo command from the Edit menu to remove an added block.

16.13 Moving Blocks in a Model

To move a single block from one place to another in a model window, drag the block to a
new location. Simulink automatically repositions lines connected to the moved block. To
move more than one block, including connecting lines:

 Select the blocks and lines


 Drag the objects to their new location and release the mouse button.

16.14 Duplicating Blocks in a Model

You can duplicate blocks in a model as follows. While holding down the Ctrl key, select the
block with the left mouse button, then drag it to a new location. You can also do this by
dragging the block using the right mouse button. Duplicated blocks have the same parameter
values as the original blocks. Sequence numbers are added to the new block names.

86
16.15 Specifying Block Parameters

The Simulink user interface lets you assign values to block parameters. Some block
parameters are common to all blocks. Use the Block Properties dialog box to set these
parameters. To display the dialog box, select the block whose properties you want to set.
Then select Block Properties from Simulink‟s Edit menu.

Other block parameters are specific to particular blocks. Use a block‟s block-specific
parameter dialog to set these parameters. Double-click on the block to open its dialog box.
You can accept the displayed values

or change them. You can also use the set_param command to change block parameters.

16.16 Block Properties Dialog Box

The Block Properties dialog box lets you set some common block parameters.

Block Properties Dialog Box

The dialog box contains the following fields:

16.17 Description

Brief description of the block‟s purpose.

I. Priority

Execution priority of this block relative to other blocks in the model.


87
Tag

A general text field that is saved with the block.

Deleting Blocks

To delete one or more blocks, select the blocks to be deleted and press the Delete or
Backspace key. You can also choose Clear or Cut from the Edit menu. The Cut command
writes the blocks into the clipboard, which enables you to paste them into a model. Using the
Delete or Backspace key or the Clear command does not enable you to paste the block later.
You can use the Undo command from the Edit menu to replace a deleted block.

16.18 Changing the Orientation of Blocks

By default, signals flow through a block from left to right. Input ports are on the left, and
output ports are on the right. You can change the orientation of a block by choosing one of
these commands from the Format menu:

 The Flip Block command rotates the block 180 degrees.


 The Rotate Block command rotates a block clockwise 90 degrees.

The figure below shows how Simulink orders ports after changing the
orientation of a block using the Rotate Block and Flip Block menu items. The text in the
blocks shows their orientation.

Effects of the Rotate and Flip block

16.19 Resizing Blocks

To change the size of a block, select it, then drag any of its selection handles. While you hold
down the mouse button, a dotted rectangle shows the new blocksize. When you release the
mouse button, the block is resized. For example, the figure below shows a Signal Generator
block being resized. The lower-right handle was selected and

88
dragged to the cursor position. When the mouse button is released, the block takes its new
size. This figure shows a block being resized.

Resizing a block

16.20 Manipulating Block Names

All block names in a model must be unique and must contain at least one character. By
default, block names appear below blocks whose ports are on the sides, and to the left of
blocks whose ports are on the top and bottom, as this figure shows.

16.21 Position of Block Names

You can edit a block name in one of these ways:


 To replace the block name on a Microsoft Windows or UNIX system, click on the
block name, then double-click or drag the cursor to select the entire name. Then,
enter the new name.
 To insert characters, click between two characters to position the insertion point,
then insert text.
 To replace characters, drag the mouse to select a range of text to replace, then enter
the new text.

When you click the pointer someplace else in the model or take any other action, the name is
accepted or rejected. If you try to change the name of a block to a name that already exists or
to a name with no characters, Simulink displays an error message.

You can modify the font used in a block name by selecting the block, then choosing the Font
menu item from the Format menu. Select a font from the Set Font dialog box. This
procedure also changes the font of text on the block icon. You can cancel edits to a block
name by choosing Undo from the Edit menu.

16.22 Disconnecting Blocks

To disconnect a block from its connecting lines, hold down the Shift key, then drag the block
to a new location.
89
16.23 Building a Simple Model

This example shows you how to build a model using many of the model building commands
and actions you will use to build your own models. The instructions for building this model
in this section are brief.
The model integrates a sine wave and displays the result, along with the sine wave. The block
diagram of the model looks like this.

Simulink Block Diagram of a simple model

To create a new model, select Model from the New submenu of the Simulink library
window‟s File menu. To create a new model on Windows, select the New Model button on
the Library Browser‟s toolbar.

New Model button Toolbar

You might want to move the new model window to the right side of your screen so you can
see its contents and the contents of block libraries at the same time.

90
To create this model, you will need to copy blocks into the model from the following
Simulink block libraries:

 Sources library (the Sine Wave block)


 Sinks library (the Scope block)
 Continuous library (the Integrator block)
 Signals & Systems library (the Mux block)

You can copy a Sine Wave block from the Sources library, using the Library Browser
(Windows only) or the Sources library window.

To copy the Sine Wave block from the Library Browser, first expand the Library Browser
tree to display the blocks in the Sources library. Do this by clicking first on the Simulink
node to display the Sources node, then on the Sources node to display the Sources library
blocks. Finally click on the Sine Wave node to select the Sine Wave block.

Locating the Sine wave block

Now drag the Sine Wave node from the browser and drop it in the model window. Simulink
creates a copy of the SineWave block at the point where you dropped the node icon.

91
Dragging a Sine wave block to the Model Window

Copy the rest of the blocks in a similar manner from their respective libraries into the model
window. You can move a block from one place in the model window to another by dragging
the block. You can move a block a short distance by selecting the block, then pressing the
arrow keys. With all the blocks copied into the model window, the model should look
something like this.

Completed Simulink Model

If you examine the block icons, you see an angle bracket on the right of the Sine Wave block
and two on the left of the Mux block. The > symbol pointing out of a block is an output port;
if the symbol points to a block, it is an input port. A signal travels out of an output port and
into an input port of another block through a connecting line. When the blocks are connected,
the port symbols disappear.

The Integrator Block

Now it‟s time to connect the blocks. Connect the Sine Wave block to the top input port of the
Mux block. Position the pointer over the output port on the right side of the SineWave block.
Notice that the cursor shape changes to cross hairs.

92
Targeting a block
Hold down the mouse button and move the cursor to the top input port of the Mux block.
Notice that the line is dashed while the mouse button is down and that the cursor shape
changes to double-lined cross hairs as it approaches the Mux block.

Connecting two blocks

Now release the mouse button. The blocks are connected. You can also connect the line to the
block by releasing the mouse button while the pointer is inside the icon. If you do, the line is
connected to the input port closest to the cursor‟s position.

93
Sine wave block connected to the input of a multiplexer
Drawing a branch line is slightly different from drawing the line you just drew. To weld a
connection to an existing line, follow these steps:
 First, position the pointer on the line between the Sine wave and the Mux Block
 Press and hold down the Ctrl key. Press the mouse button, then drag the
pointer to the input port of the integrator block

Creating a branch

 Release the mouse button. Simulink draws the line between the starting point
and the Integrator block‟s input port.

Finish making block connections. When you‟re done, your model should look something like
this.

94
Final Simulink Model
Choose Start from the Simulation menu and watch the traces of the Scope block‟s input.

Scope displaying model Simulation


The simulation stops when it reaches the stop time specified in the Simulation Parameters
dialog box or when you choose Stop from the Simulation menu.
To save this model, choose Save from the File menu and enter a filename and location. That
file contains the description of the model.
To terminate Simulink and MATLAB, choose Exit MATLAB (on a Microsoft Windows
system) or Quit MATLAB .You can also type quit in the MATLAB command window. If
you want to leave Simulink but not terminate MATLAB, just close all Simulink windows.

16.24 Creating Subsystems

As the model increases in size and complexity, you can simplify it by grouping blocks into
subsystems. Using subsystems has these advantages:

 It helps reduce the number of blocks displayed in your model window.


 It allows you to keep functionally related blocks together.

95
 It enables you to establish a hierarchical block diagram, where a Subsystem
block is on one layer and the blocks that make up the subsystem are on
another.

You can create a subsystem in two ways:

 Add a Subsystem block to your model, then open that block and add the
blocks it contains to the subsystem window.
 Add the blocks that make up the subsystem, then group those blocks into a
subsystem.

16.25 Creating a Subsystem by Adding the Subsystem Block

To create a subsystem before adding the blocks it contains, add a Subsystem block to the
model, then add the blocks that make up the subsystem:

 Copy the Subsystem block from the Signals & Systems library into your
model.
 Open the Subsystem block by double-clicking on it.
 In the empty Subsystem window, create the subsystem.

Use Inport blocks to represent input from outside the subsystem and Outport blocks to
represent external output. For example, the subsystem below includes a Sum block and Inport
and Outport blocks to represent input to and output from the subsystem:

Summing input Subsystem

16.25 Creating a Subsystem by Grouping Existing Blocks

If your model already contains the blocks you want to convert to a subsystem, you can create
the subsystem by grouping those blocks:

 Enclose the blocks and connecting lines that you want to include in the
subsystem within a bounding box. You cannot specify the blocks to be
grouped by selecting them individually or by using the Select All command.

For example, this figure shows a model that represents a counter. The Sum and Unit Delay
blocks are selected within a bounding box.

96
Creating a Subsystem of select blocks

When you release the mouse button, the two blocks and all the connecting lines are selected.
 Choose Create Subsystem from the Edit menu. Simulink replaces the
selected blocks with a Subsystem block.
This figure shows the model after choosing the Create Subsystem command (and resizing
the Subsystem block so the port labels are readable).

Created Subsystem

If you open the Subsystem block, Simulink displays the underlying system, as shown below.
Notice that Simulink adds Inport and Outport blocks to represent input from and output to
blocks outside the subsystem.

Contents of the Subsystem

As with all blocks, you can change the name of the Subsystem block.

16.26 Labelling Subsystem Ports

Simulink labels ports on a Subsystem block. The labels are the names of Inport and Outport
blocks that connect the subsystem to blocks outside the subsystem through these ports. You
can hide the port labels by selecting the Subsystem block, then choosing Hide Port Labels
from the Format menu. You can also hide one or more port labels by selecting the
appropriate Inport or Outport block in the subsystem and choosing Hide Name from the
Format menu. This figure shows two models. The subsystem on the left contains two Inport
blocks and one Outport block. The Subsystem block on the right shows the labeled ports.

97
Subsystem labels

Assignment Question

98

You might also like