Professional Documents
Culture Documents
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
NAME: ______________________________
SEMESTER/YEAR: ___________________________
ROLL NO:_____________________________________
BATCH :_____________________________________
DEPARTMENT:_____________________________________
1
Signals and Systems
Using Matlab Toolbox
Computer Laboratory Workbook
By
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
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.
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
7
6. Power calculations of signals ………………………………
6.1 Calculation of Signal Power
6.2 Continuous Time Case
6.3 Discrete Time Case
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
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
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.
11
Lab 01
Introduction to MATLAB
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
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
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
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.
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.
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]';
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.
16
Lab 2
Elementary Signals and Basic Signal Operations
Sinusoidal Signal
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] .
%% 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
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
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
21
stem(n,impulse3); % plot discrete values of n versus values of
impulse3
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');
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
>>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
>> 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 =
0 0 0 0 0 0 0 0 0 0
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
>>
>> t=0:0.005:1;
>> f_t=exp(-5.*t).*sin(2*pi*440*t);
>> plot(f_t)
>> plot(t,f_t)
28
Lab 04
Constructing the different exponential signals and User Defined functions
( ) ; j is complex operator
( )
x(t)=
29
Fig: General exponential signal
%% Real exponential (Decaying)
30
Fig: Plot of Exponential Signals
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
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
MATLABB CODE
a=input('enter the a = ');
33
b=input('enter the phi = ');
34
Lab 05
Constructing periodic signals from harmonically related sinusoidal signals
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
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.
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
>> 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)
>> 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.
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
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));
Figure 7.01 The test signal that will be used in transformation examples.
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.
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
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.
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.
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
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) =
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
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
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.
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
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
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
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;
57
58
Lab 11
Studying Fourier and Laplace Transform and its inverse functions practically
>> 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)
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)
1 () Dirac(t) 1 1
61
4 1/t i*pi*(1-2*heaviside(w)) laplace(1/t,t,s)
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),
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.
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)
n0 n0
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)
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)]
MATLAB Code
syms Z n
64
ans=iztrans(3*Z/(Z+1))
return
ans =3*(-1) ^n
>> pretty(ans)
n
3 (-1)
>>
Z – TRANSFORM
Result:
ans = 4*z/(4*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)
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)
Result:
roots (d) =
0.7581 + 0.5508i
0.7581 - 0.5508i
roots (n) =
0.8090 + 0.5878i
0.8090 - 0.5878i
69
Pole-Zero Diagram
zplane(num,den); % there are 2 real poles, 1 pair of imaginary poles and 2 pairs
of imaginary zeros
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)
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
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)
Result
numA = 1.0000 2.0000 4.0000 2.5000 1.0000
denA = 1.0000 18.0000 1.5000 1.0000 0.5000
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),
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
-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)
a = [1 –1.8*cos(pi/16) 0.81];
b = [1 ½] ;
figure; impz(b,a); grid
[ r c l ] = residuez (b,a) ;
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)
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
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
14.2 Description:
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
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
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 j2kn / N k = 0, 1, … , N-1
n0
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 j2kn / 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
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
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.
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
x = [1 4 9 11 8 3];
X1 = fft(x,512); % 512-pt. DFT
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.
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.
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:
83
Relational operators
Conversion/saturation of fixed-point signals
Switch between two values
Delay
Delta-inverse operator
Monitoring signals
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.
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.
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.
The Windows version of Simulink displays a status bar at the bottom of each model and
library window.
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.
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:
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.
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:
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.
The Block Properties dialog box lets you set some common block parameters.
16.17 Description
I. Priority
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.
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 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.
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
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.
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.
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.
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.
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:
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.
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.
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.
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.
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.
As the model increases in size and complexity, you can simplify it by grouping blocks into
subsystems. Using subsystems has these advantages:
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.
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.
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:
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.
As with all blocks, you can change the name of the Subsystem block.
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