Anda di halaman 1dari 312


Ph. D., IIT Delhi
Professor and Coordinator IIPC
Shri Sankaracharya College of Engineering
& Technology, Bhilai
Dr. R.N. Patel, email: 2
Introduction to MATLAB
What is Matlab?
Matlab is basically a high level language which
has many specialized toolboxes for making
things easier for us
How high?

High Level
Languages such as
C, Pascal etc.
Dr. R.N. Patel, email: 3
MATLAB = MATrix LABoratory
Official Website:,
Advantages of MATLAB
Ease of use
Platform independence
Predefined functions
Disadvantages of MATLAB
Can be slow
Commercial software
Dr. R.N. Patel, email: 4
What is MATLAB?
MATLAB is a high-performance language for technical
computing. It integrates computation, visualization,
and programming in an easy-to-use environment
where problems and solutions are expressed in
familiar mathematical notation. Typical uses include:

Math and computation
Algorithm development
Modeling, simulation, and prototyping
Data analysis, exploration, and visualization
Scientific and engineering graphics
Application development, including Graphical User
Interface building

Dr. R.N. Patel, email: 5
What is MATLAB?

MATLAB is an interactive system whose basic data element is an
array that does not require dimensioning. This allows you to
solve many technical computing problems, especially those
with matrix and vector formulations, in a fraction of the time
it would take to write a program in a scalar non-interactive
language such as C or Fortran.

MATLAB features a family of application-specific solutions called
toolboxes. Very important to most users of MATLAB,
toolboxes allow you to learn and apply specialized technology.
Toolboxes are comprehensive collections of MATLAB functions
(M-files) that extend the MATLAB environment to solve
particular classes of problems. Areas in which toolboxes are
available include signal processing, control systems, neural
networks, fuzzy logic, wavelets, simulation, and many others.

Dr. R.N. Patel, email: 6
MATLAB is the leading computational
software for
Product design and development
Research in industry and academia
Technical education

Over 400,000 MATLAB users worldwide
Used in over 100 countries
For the purposes of an engineer or scientist, MATLAB has
the most features and is the best developed program in
its class. -IEEE Spectrum, Software Review, February 1997
Dr. R.N. Patel, email: 7
MATLAB Customers
Commercial - US
Allied Signal
Bell Helicopter
Pratt and Whitney
Raytheon Sys. Co.
Airbus Consortium
British Aerospace
Spar Aerospace
Air Force (US and
Canadian Space
European Space
Ministry of Def
NASA (all facilities)
Navy (US and others)
Dr. R.N. Patel, email: 8
Notable Projects Using MATLAB
Space Maneuvering Vehicle
Deep Space Probe
International Space Station
Next Generation Space Telescope

I have been amazed at how MATLAB can boost ones
productivity. Anything from simple analysis to complex
modeling and simulation can be done in a fraction of the
time it would take to write your own code.

Gregory E. Chamitoff, Ph.D.
NASA, Johnson Space Center
Dr. R.N. Patel, email: 9
The MathWorks Products
Control System
Robust Control
Nonlinear Control
Quantitative Fback
LMI Control
Model Predictive
& Code generation
Real-Time Workshop
Fixed Point Blockset
RTW Ada Extension

Signal Processing
Signal Processing
DSP Blockset
MATLAB Compiler

System ID
System ID
Symbolic Math

Image Processing
Power System Block Set
Fuzzy Logic
Financial Toolbox
Partial Differential Eqns
Neural Network

ADI (Beacon)
VxWorks - Wind River
SD/Fast - Symbolic Dynamics
Maple V - Waterloo Maple
Saber - Analogy
Teamwork - CADRE
Dr. R.N. Patel, email:
Introduction to MATLAB
Dr. R.N. Patel, email: 11
1.1 Introduction
1.2 The MATLAB Desktop
1.2.1 The Command Window
1.2.2 The Command History Window
1.2.3 Current Directory Browser
1.2.4 Workspace and Array Editor
1.2.5 The Help Browser
1.2.6 The Edit/Debug Window
1.2.7 Path Browser
1.3 Getting Help from Command Window
1.4 General Syntax
1.5 Writing Simple Expressions
1.6 Screen Display Control
1.7 MATLAB Demonstrations
1.8 How to Quit MATLAB ?

Dr. R.N. Patel, email: 12
Getting Started
To start MATLAB, double-click the icon named MATLAB
on your PCs desktop and the MATLAB working
environment pops up. This is an interactive
environment, i.e., you can start entering commands
and obtain results instantly. In the MATLAB
environment, you can see a menubar at the top of
the screen and the command window along with
some other windows occupy the rest of the screen.
In the MATLAB command window, a command can be
executed by typing it at the MATLAB prompt ( >> )
and pressing the ENTER key.
Dr. R.N. Patel, email: 13
The MATLAB Desktop
Dr. R.N. Patel, email: 14
The Command Window

A user can assign values to the variables and write
expressions at the command prompt (>>) in the
command window and they can be executed
instantaneously. As a simple example, try
entering the following commands and observe
the results in your MATLAB command window:

>> a = 4+3*2
>> c = 24/3;
>> b = a+c
Dr. R.N. Patel, email: 15
Variables in MATLAB
No need for types. i.e.,

All variables are created with double precision unless
specified and they are matrices.

After these statements, the variables are 1x1 matrices with
double precision

int a;
double b;
float c;
Dr. R.N. Patel, email: 16
Variables and Arrays
Array: A collection of data values organized into rows and
columns, and known by a single name.
Row 1
Row 2
Row 3
Row 4
Col 1 Col 2 Col 3 Col 4 Col 5
Variables in MATLAB
Dr. R.N. Patel, email: 17
The fundamental unit of data in MATLAB
Scalars are also treated as arrays by MATLAB (1 row
and 1 column).
Row and column indices of an array start from 1.
Arrays can be classified as vectors and matrices.
Variables in MATLAB
Dr. R.N. Patel, email: 18
Vector: Array with one dimension

Matrix: Array with more than one dimension

Size of an array is specified by the number of rows and
the number of columns, with the number of rows
mentioned first (For example: n x m array).
Total number of elements in an array is the product of
the number of rows and the number of columns.
Variables in MATLAB
Dr. R.N. Patel, email: 19
Variable names must begin with a letter, followed by any
combination of letters, numbers and the underscore (_)

The MATLAB language is Case Sensitive: NAME, name and
Name are all different variables.
Give meaningful (descriptive and easy-to-remember) names
for the variables. Never define a variable with the same
name as a MATLAB function or command.
Dr. R.N. Patel, email: 20
Common types of MATLAB variables

double: 64-bit double-precision floating-point numbers
They can hold real, imaginary or complex numbers in the
range from 10
to 10
with 15 or 16 decimal digits.
>> var = 1 + i ;

char: 16-bit values, each representing a single character
The char arrays are used to hold character strings.

>> comment = This is a character string ;

The type of data assigned to a variable determines the type of
variable that is created.
Variables in MATLAB
Dr. R.N. Patel, email: 21
The Command History Window

It displays a list of the commands that a user has entered in the
Command Window .The commands remain in the list until they
are deleted. A section of these commands can be selected by
using (Shift + Arrow) keys and can be executed by pressing ENTER
(alternatively you can also use Copy and Paste), without typing
them again. If you wish to execute the previously executed
commands, press UP () arrow key at the command prompt.
Typing the first letter/word of any previous entry, followed by an
UP() arrow displays all the pervious entries beginning with that
letter/word in sequence. The command can be then re-executed
by pressing ENTER. At your command prompt, press UP() arrow
twice or type c and press UP() arrow key once to re-execute or
modify the following statement:

>> c = 24/3;
Dr. R.N. Patel, email: 22
Dr. R.N. Patel, email: 23
Current Directory Browser
You can set the current working directory of MATLAB by typing
the path of a particular folder over the Current Directory
window in the MATLAB Desktop. Alternatively, you can
also use the icon
to browse and set the current working directory. Then set
the current directory to a folder where your files are
stored. For example, C:\MATLAB6p5\work is shown as
current working directory in Figure 1. MATLAB would look
for files for execution in current working directory.
Dr. R.N. Patel, email: 24
Workspace and Array Editor

When you issue commands like:

>> x = 10;
>> y = [1 2 3 4]; % Array variable

MATLAB creates variables named x and y, and saves them in a part of
computer memory known as Workspace. The symbol % is
used in MATLAB for inserting the comments for the clarity of
the codes. Anything written after % in a line is not executed
(even if it is an executable statement or expression).
Dr. R.N. Patel, email: 25
You can observe the contents of the Workspace by typing the
whos command

Double-clicking on any variable in the Workspace Browser
Window brings up the Array Editor which allows the user to
observe and modify the information stored in the variable. Any
variable on Workspace can be manipulated using the array
Dr. R.N. Patel, email: 26
Change the display format Change the values of the
array elements
MATLAB Array Editor
MATLAB Workspace

Dr. R.N. Patel, email: 27
The Help Browser

The ? icon on the MATLAB desktop launches the Help
Window, which provides links to the documentation on all
the components (or toolboxes) for your MATLAB version. It
provides an important and dynamic reference for working

There is another simpler way to get help on different functions
e.g. by typing

>> help sqrt at the command prompt.

You get the help on function sqrt.
Dr. R.N. Patel, email: 28
Dr. R.N. Patel, email: 29
The Edit/Debug Window
The MATLAB Editor/Debugger provides a graphical user interface for basic text
editing, as well as for M-file debugging. The Editor/Debugger is a single tool
that can be used for editing, debugging, or both.

The Edit/Debug Window is essentially a programming text editor, with the MATLAB
language features highlighted in different colors. Instead of writing the
commands directly in the Command Window, a series of commands may be
placed into a file known as script file or M-file (saved with extension .m).
The entire file can be executed just by typing its name (without extension
name) at the command prompt. For example, consider the following file

Dr. R.N. Patel, email: 30
x = 10;
y = x/4;
z = y*9;

This can be executed in command space in the
following manner (assuming the file is in the current
working directory):

>> simple
Dr. R.N. Patel, email: 31
Path Browser

The Path Browser allows you to view and modify the MATLAB
search path. It allows the user to add, delete, or change the
order of directories in the path. Make sure that the folder
where you have saved your M-file exists in MATLAB Path,
otherwise it wont be executed. Also, if there are more
than one functions, commands or script files (M-files) with
the same name, the first one found in the search path will
be executed and all the others will be inaccessible.
Therefore, it is extremely important not to define a variable
with the same name as a standard MATLAB function or
command, which will make that function inaccessible !!
Dr. R.N. Patel, email: 32
Dr. R.N. Patel, email: 33
Getting Help from Command Window

To access help from command window, type help at the MATLAB prompt
and press ENTER. e.g.

>> help

>> help plot

To search a particular topic by title, the lookfor command proves useful.
For example, to find out what facility MATLAB provides on computing
integral of a function, you can give the following command:

>> lookfor integral

The output of this is a list of several functions that are related to integrals
and contain the word integral in their help documentation.

Dr. R.N. Patel, email: 34

Other important commands with similar purpose are:

what : lists the MATLAB related files found in
the current working directory,

dir : lists all files in the current working directory,

which FUNCT : displays the full pathname of the function with
the name FUNCT.

You can also learn how to effectively use help command by typing the

>> help help
Dr. R.N. Patel, email: 35
General Syntax

MATLAB automatically creates a variable in the memory as soon as it is
assigned a value. The variable names must begin with a letter, followed by
any combination of letters, numbers and the underscore (_ ) character.
Variable names are case sensitive, in the sense that the uppercase and
lowercase letters are distinguished. For example, a variable named Value
is different from value and so also from vaLue. Similarly, MULT, mult
and Mult are three different variables.

MATLAB requires that all variable names (except for those used by symbolic
toolbox) be assigned numeric values prior to being used in an expression.
For example:

>> a=2.3;
>> b = 4.7;
>> d = c + a*b;
MATLAB responds as:
??? Undefined function or variable 'c'.

Dr. R.N. Patel, email: 36
Special Values
MATLAB includes a number of predefined special values.
These values can be used at any time without initializing
These predefined values are stored in ordinary variables.
They can be overwritten or modified by a user.
If a new value is assigned to one of these variables, then
that new value will replace the default one in all later
>> circ1 = 2 * pi * 10;
>> pi = 3;
>> circ2 = 2 * pi * 10;
Never change the values of predefined variables.
Dr. R.N. Patel, email:
Special Values
pi: t value up to 15 significant digits
i, j: sqrt(-1)
Inf: infinity (such as division by 0)
NaN: Not-a-Number (division of zero by zero)
clock: current date and time in the form of a 6-element
row vector containing the year, month, day, hour,
minute, and second
date: current date as a string such as 16-Feb-2004
eps: epsilon is the smallest difference between two
ans: stores the result of an expression
Dr. R.N. Patel, email:
Several variables (or expressions) can also be defined in the same line, separated by
a comma (,) or a semicolon (;). When a comma is used, the system displays the
variable and its value on the command line. For example, when you type the

>> x=1.1, y=3.3, z=5.5
MATLAB responds with the following display:
x =
y =
z =

The use of semicolons in place of the commas would suppress the outputs, e.g.

>> x=3.5; y=1.9; z=2.75;
the command window does not display the values as was done in the former case.

Dr. R.N. Patel, email: 39
Writing Simple Expressions

Unlike many other programing languages, you need not declare the type of
values a variable can take in MATLAB. For example, a variable a can
take an integer value, and in the next step, you can assign the same
variable a float value and in the third step, you can assign it a string
and so on. Here is an example:

>> newvar = 5
newvar =

>> newvar = 20.197
newvar =

>> newvar = 'surabhi'
newvar =
Dr. R.N. Patel, email: 40
Operators (arithmetic)
+ addition
- subtraction
* multiplication
/ division
^ power
complex conjugate transpose

Dr. R.N. Patel, email: 41
Operators (relational, logical)
== Equal to
~= Not equal to
< Strictly smaller
> Strictly greater
<= Smaller than or equal to
>= Greater than equal to
& And operator
| Or operator

Dr. R.N. Patel, email: 42
Writing Simple Expressions
variable_name = expression;

addition a + b a + b
subtraction a - b a - b
multiplication a x b a * b
division a / b a / b
exponent a
a ^ b
Dr. R.N. Patel, email:
Hierarchy of operations

x = 3 * 2 + 6 / 2
Processing order of operations is important
parentheses (starting from the innermost)
exponentials (from left to right)
multiplications and divisions (from left to right)
additions and subtractions (from left to right)

>> x = 3 * 2 + 6 / 2
x =
Dr. R.N. Patel, email:
The parentheses ( ) are used in complex operations. Other
braces (such as { } and [ ] ) are reserved for special
purposes in MATLAB. Here are some examples of
writing simple expressions:
Mathematical Expression MATLAB Code
1. x + 2y 3 (y-x)
2. 2 x
+ 5/x

3. 5 x
+ 9 y

4. 3 tan(x)/ (1+ sin
x + 2*y 3* (y-x)
2*x^3 + 5/x^5
5*x^(1/3) + 9*y^(0.173)
3*tan (x) / (1+(sin(x))^2)
Dr. R.N. Patel, email:
Screen Display Control (The "format" function):

MATLAB performs numeric computations in double-precision format. The
number of digits after the decimal of a floating point number can be
controlled by using the format command. The following code illustrates
the usage of format command:

>> format % this is same as 'format short', the
% default format
>> pi % pi has a pre-defined value in MATLAB
ans =
>> format long % change the display format to long
>> pi
ans =
Dr. R.N. Patel, email: 46
>> format long e
>> pi
ans =
>> format hex
>> pi
ans =

Dr. R.N. Patel, email: 47
>> format compact
>> x = 2, y = 3,
x =
y =
This results in the values being displayed, but the display is
compact to save your Desktop area.

See >> help format for more details on the other display formats
available with MATLAB.
Dr. R.N. Patel, email: 48
Changing the data format

>> value = 12.345678901234567;
format short 12.3457
format long 12.34567890123457
format short e 1.2346e+001
format long e 1.234567890123457e+001
format short g 12.346
format long g 12.3456789012346
format rat 1000/81
Dr. R.N. Patel, email:
MATLAB Demonstrations

MATLAB is shipped with a number of
demonstration programs. Use help demos to
find out more about these. You can also type
demo on the MATLAB prompt to enter the
demonstration programs. The number of
demos depends upon the version of MATLAB
that you have.
Dr. R.N. Patel, email: 50
How to Quit MATLAB ?

You can leave a MATLAB session by typing quit
or by typing exit at the MATLAB prompt. If
MATLAB session enters into an infinite loop,
you can interrupt the running of the program
by a Ctrl+c command the from keyboard,
and thus you would get back to the command
Dr. R.N. Patel, email: 51

help command Online help
lookfor keyword Lists related commands
which Version and location info
clear Clears the workspace
clc Clears the command window
diary filename Sends output to file
diary on/off Turns diary on/off
who, whos Lists content of the workspace
more on/off Enables/disables paged output
Ctrl+c Aborts operation
% Comments
Dr. R.N. Patel, email: 52
Exercise 1: Use MATLAB to make the following calculations, for given values of x and
check the results with the help of a calculator:
y = ( 1 1/x3)-1, x = 2
y = 3. x2, x = 3
y = 7(x1/3) + 4x0.58, x = 20
y = elog(x), x = 3
Exercise 2: Given an expression: f = x + 2 {y 3 (z-t)}, explain with the reasoning what
are the problems with the following codes in MATLAB:
f = x + 2 {y 3 (z-t)}
f = x + 2*[y 3 (z-t)]
f = x + 2 (y 3 (z-t))
f = x + 2*(y 3 (z-t))
Subsequently, write the correct code for the expression and compute it with the
values x = 2, y = 3, z = 5 and t = 7.
Dr. R.N. Patel, email: 53
Exercise 3: The MATLAB expression >> sin^2(30) + cos^2(30) does
not result in expected value of 1. What are the possible
problems with this code?
Exercise 4: Type demo on MATLABs command prompt and then
press ENTER to explore what it contains. Locate the
demonstration programs for 2-D plots on the same.
Exercise 5: What are the different ways to use MATLAB help on a
particular function? Find the syntax and usage of the function
log with MATLAB help.
Exercise 6: Suppose you do not know what is the MATLAB
function for finding inverse of sine function. How would you
get the help on it?
Exercise 7: Use MATLAB to verify the identity e j = cos () + j sin
(), taking any three values of variable .

Dr. R.N. Patel, email: 54
Vectors, Matrices and Operators in MATLAB
Dr. R.N. Patel, email:
The MATLAB Array
Creating Vectors and Matrices
Creating Sub Matrices of a Given Matrix
Changing the Elements of a Given Matrix
Creating Special Matrices
Matrix Operators
Matrix Multiplication and Inversion
Array operators
Relational Operators
Logical Operators
Properties of a Matrix
Replicating Data to Form a Matrix
Dr. R.N. Patel, email: 56
The MATLAB Array
MATLAB works with only a single object type, the
MATLAB array. All MATLAB variables, including
scalars, vectors, matrices, strings, etc., are stored
as MATLAB arrays. A matrix or a vector can be
treated as an array according to the context.
When the array has only one dimension (either a row
or a column) it is known as a vector, while two or
more dimensional array is known as a matrix.
It is important to note that in MATLAB even a scalar is
treated as an array with dimension 11. A
character string is also treated as an array. Observe
the following examples:
Dr. R.N. Patel, email: 57
>> A1=[1,2,3,4,5] % A1 is a vector
>> A2=[1 2 3 4 5] % A2 is a vector same as A1
>> B=[1,4,7;2,5,8;3,6,9] % B is a matrix
>> C= 'Sitaram' % C is a string array

By typing the above at the command prompt, MATLAB echoes as follows:

A1 =
1 2 3 4 5
A2 =
1 2 3 4 5
B =
1 4 7
2 5 8
3 6 9
C =
Dr. R.N. Patel, email: 58

Arrays are constructed using brackets [ ] and semicolons. All of
the elements of an array are listed in row order.

The values in each row are listed from left to right and they are
separated by blank spaces or commas.

The rows are separated by semicolons or new lines.

The number of elements in every row of an array must be the
Dr. R.N. Patel, email: 59
The elements of a vector or a matrix are accessed using
parentheses operator. Inside the parentheses is the index of
the element. Consider the following examples:

>> A1(2) % indicates second element of array a.
ans =
>> B(1,3)
ans =
>> C(1)
ans =
Dr. R.N. Patel, email: 60
The length of a vector can be determined by length command, whereas the
order of a matrix is determined using size command. Consider the previous
examples again:
>> A=[1,2,3,4,5]
A =
1 2 3 4 5
>> length(A) % gives the length (i.e., no. of elements) of the vector a
ans =
>> B=[1,4,7;2,5,8;3,6,9]
B =
1 4 7
2 5 8
3 6 9
>> size(B) % gives the order of the given matrix
ans =
3 3
Dr. R.N. Patel, email: 61
>> [m n]=size(B) % returns the number of rows and columns in b as
% separate output variables
m =
n =
>> C= 'Sitaram'
C =
>> length(C)
ans =
>> C(length(C)-2) % This is equivalent to writing >> c(7-2)
ans =
You can also access the last element in a vector using end variable as shown below:
>> C(end) % Access the last element
ans =

MATLAB automatically interprets the variable end as the last element of a particular vector. In
other words, end = length(C) in relation to the above example.
Dr. R.N. Patel, email: 62
Creating Vectors and Matrices

A common way to create vector is to put the elements of the vector separated by
space in square brackets [ ] as shown below:
>> VEC1 = [10 12 0 1 5 8 9 10 20]
VEC1 =
10 12 0 1 5 8 9 10 20

Sometimes the number of vector elements could be large. In such cases, you can use
the three continuous dots ( ) to break the array in several lines. Consider
the following example showing the creation of a vector B with 12 elements:
>> B =[1 2 3 4 ...
5 6 7 8 ...
9 10 11 12]
B =
1 2 3 4 5 6 7 8 9
10 11 12
Dr. R.N. Patel, email: 63
Another important way to create vectors is to use the colon notation (:). This is
especially useful if the vector elements are to be uniformly spaced. A general
method to create a vector V is as follows:

V = s:d:f
s= start or initial value
d= increment/decrement step
f= end or final value

The vector V then contains elements [s s+d s+2d s+3d s+kd] where k is chosen
such that s+kd less than or equal to f. The following examples illustrate the use
of colon operator:

>> 1:2:10
ans =
1 3 5 7 9

Dr. R.N. Patel, email: 64

>> X = 2*pi:-pi/2:-2*pi
X =
Columns 1 through 7
6.2832 4.7124 3.1416 1.5708 0 -1.5708 -3.1416
Columns 8 through 9
-4.7124 -6.2832

When increment/decrement step d is omitted, MATLAB assumes d=1.
Following are some examples using the colon operator to generate

>> 1:10
ans =
1 2 3 4 5 6 7 8 9 10
>> Y = -pi: pi
Y =
-3.1416 -2.1416 -1.1416 -0.1416 0.8584 1.8584 2.8584

Dr. R.N. Patel, email: 65
Another important way to create uniformly separated elements
in a vector is by using the linspace command. The command
>>linspace(x1, x2, n) generates n points between two
numbers x1 and x2. For n < 2, linspace returns x2.
If n equally spaced values on a logarithmic scale are desired then
you can use:
Y = logspace(x1,x2,n)
In this case, the first element of the resultant array y, is 10
the last element is 10
and the total number of elements is n.
The following are a few examples of vector creation using
linspace and logspace commands:
Dr. R.N. Patel, email: 66
>> p = linspace(100, 20, 9)
p =
100 90 80 70 60 50 40 30 20
>> q = logspace(1, 5, 5)
q =
10 100 1000 10000 100000
Dr. R.N. Patel, email: 67
Creating Sub Matrices of a Given Matrix:

MATLAB supports several ways to create and access the part of a
matrix. One can access one element, a row, a column or a sub-
matrix. For example:

>> A = [1 3 5; 2 4 6; 11 9 7; 3 4 5]
A =
1 3 5
2 4 6
11 9 7
3 4 5

The following are the different ways to create and access parts of
matrix A:

A(i, j) returns the (i, j) entry of the matrix A.

Dr. R.N. Patel, email: 68

>> A(3,1) % (3rd row, 1st Column) entry
ans =
>> A(2,3)
ans =
>> A(2,4)
??? Index exceeds matrix dimensions.
A(2,4) results in an error because the matrix A has only 3 columns.

A(i, :) returns the ith row of A.
>> A(2,:)
ans =
2 4 6
A(:, j) returns the jth column of A. The output is a column vector
>> A(:,3)
ans =
Dr. R.N. Patel, email: 69
A(2 : 4, 1 : 2) returns rows from 2 to 4 and columns from 1 to 2.
Thus a 32 matrix is returned as shown below:
>> A(2 : 4, 1 : 2)
ans =
2 4
11 9
3 4
You can also access rows 2 to rows 4 with all columns by A(2:4, :)
as shown below:
>> A(2:4,:)
ans =
2 4 6
11 9 7
3 4 5
Dr. R.N. Patel, email: 70
A([2 4], :) returns rows 2 and 4 and all columns. The output is 2 3 matrix as shown
>> A([2 4], :)
ans =
2 4 6
3 4 5

A(:) returns one long column combining the columns of A as follows:

>> A(:)
ans =
Dr. R.N. Patel, email: 71
Changing the Elements of a Given Matrix

Suppose a given matrix is:

>> A = [9 1 7; 2.5 7.5 12; 5 6.2 11]
A =
9.0000 1.0000 7.0000
2.5000 7.5000 12.0000
5.0000 6.2000 11.0000

You can change certain elements in the matrix without modifying the value of
other elements as below:
This example illustrates how you can change one entry at a time:

>> A(3, 2) = 7 % resets the (3, 2) entry to 7
A =
9.0000 1.0000 7.0000
2.5000 7.5000 12.0000
5.0000 7.0000 11.0000
Dr. R.N. Patel, email: 72
Since the given matrix has changed now, the next operation will be
performed over this changed matrix.
The following examples show how you can change a row or a column
of a matrix:

>> A(3, :) = [7 1 9] % resets the third row
A =
9.0000 1.0000 7.0000
2.5000 7.5000 12.0000
7.0000 1.0000 9.0000

>> A(:,1) = [1 2]
??? Error

The error in above assignment comes because of dimension mismatch.
Since A(:,1) is a column vector of length 3, it can only be assigned a
vector that is of length 3.
Dr. R.N. Patel, email: 73
You can also delete rows and columns by using colon operator
and an empty pair of square brackets. Consider the following
example where 1st row of A is deleted:

>> A(1,:)=[ ] % this expression implies that
% the 1st row of the matrix gets the new
% value as a NULL vector, i.e., 1st row is eliminated.

A =
2.5000 7.5000 12.0000
7.0000 1.0000 9.0000
Dr. R.N. Patel, email: 74
Creating Special Matrices

There are some special commands like ones, zeros, and eye in MATLAB to
create special matrices. These are especially useful for initializing all the
elements of matrix to a particular value. Let us say you want to create a
matrix with all of its elements initialized to a value 3.

>> A = 3* ones (2,4) % Creates a 2 4 matrix
A =
3 3 3 3
3 3 3 3
>> A = 3 * ones(3) % Creates a 3 3 matrix
A =
3 3 3
3 3 3
3 3 3
Dr. R.N. Patel, email: 75
Similarly, you can create a matrix with all of its elements initialized to
zero with another special function zeros:
>> B = zeros(3)
B =
0 0 0
0 0 0
0 0 0
An Identity matrix of order 33 can be created using eye command as
shown next:
>> C = eye (3)
C =
1 0 0
0 1 0
0 0 1
Dr. R.N. Patel, email: 76
In many applications like neural network learning, a matrix with random
numbers is required. The command rand generates a matrix with
randomly generated numbers chosen from a uniform distribution on the
interval (0.0,1.0).

>> D = rand (2,4)
D =
0.6038 0.1988 0.7468 0.9318
0.2722 0.0153 0.4451 0.4660

You can create a vector using any of abovementioned commands as the
following example illustrates:
>> X = rand(1,4)
X =
0.8913 0.7621 0.4565 0.0185
Dr. R.N. Patel, email: 77
>> d = [1 3 5 7], A = diag(d)
d =
1 3 5 7
A =
1 0 0 0
0 3 0 0
0 0 5 0
0 0 0 7

The magic function creates a square matrix in which the sum of elements in
all columns and rows and the two diagonals are equal. Consider the
following example:

>> z = magic(3) % gives the following matrix
z =
8 1 6
3 5 7
4 9 2
Dr. R.N. Patel, email: 78

Larger matrices can be formed by concatenating smaller matrices.
The pair of square brackets, [ ], is also known as the
concatenation operator. The basic idea behind concatenation is
that two matrices A and B can be concatenated as [A B] to form a
larger matrix C provided the dimensions of A and B match for
concatenation (in this case, the number of rows should be same
for both A and B).

>> V = [-5, 2:7, 10] % V is a concatenated vector.
% Note the middle vector is 2:7
V =
-5 2 3 4 5 6 7 10
Dr. R.N. Patel, email: 79
>> A= eye(2) % A is a matrix
A =
1 0
0 1

>> B = 2*ones(2) % B is a matrix
B =
2 2
2 2

>> C = [A B] % creates the augmented matrix
C =
1 0 2 2
0 1 2 2
Dr. R.N. Patel, email: 80
You can also place a matrix B below another matrix A by using C= [A;B]. This
is like an extension of semicolon (;) notation indicating a new line in
formation of a matrix. The new matrix C would have same number of
columns as A and B.

>> D = [A;B]
D =
1 0
0 1
2 2
2 2

>> E = [A 2*A; ones(2,2)*4 zeros(2,2)] % a concatenated matrix
E =
1 0 2 0
0 1 0 2
4 4 0 0
4 4 0 0
Dr. R.N. Patel, email: 81
The operators can be divided into three
general categories:
(a) Matrix operators and operators
used in general algebra,
(b) Relational operators and,
(c) Logical operators.

Matrix Operators
The following table summarizes the
matrix operators available in
The order of precedence for these
operators is as follows:
^ / \ * + -
The order of precedence can be modified by
using the parenthesis ( ) which gets the
highest priority
Symbol Operation
+ Addition
- Subtraction or
* Multiplication
^ Power
' Transpose (real) or
Conjugate transpose
.' Transpose (real or
\ Left division
/ Right division
Dr. R.N. Patel, email:
You can apply scalar multiplication, addition, subtraction and
power operators on a vector and matrices using the above
operators. Consider the following example where you would
like to add 2 to all the elements in vector A:
>> A = [1 2 3 4 5 6 9 8 7]
A = 1 2 3 4 5 6 9 8 7
>> B = A + 2
B = 3 4 5 6 7 8 11 10 9
Dr. R.N. Patel, email: 83
>> A * 4
ans =
4 8 12 16 20 24 36 32 28
>> C = [2 3 4]*(2 + 3^2)
C =
22 33 44
The similar rules hold good for subtraction and division operation of an array
with a scalar. However, when you apply power (^) with a matrix A, it
implies matrix multiplication as shown in the following example:
>> A = [1 2; 3 4]
A =
1 2
3 4
>> A^2 % MATLAB inteprets A^2 as A*A
ans =
7 10
15 22
Dr. R.N. Patel, email: 84
The operators can also be applied to vectors and matrices as
>> A = [1 2 3 4 5 6 9 8 7];
>> B = A + 2;
>> C = A + B
C =
4 6 8 10 12 14 20 18 16
Subtraction of vectors of the same length works exactly the same
>> D = [2,3,4]-[1 2 3]
ans =
1 1 1
However, two vectors of unequal size cannot be added and
hence, the following is an error:
>> E = [2 3 4] + [1 2]
??? Error using ==> +
Matrix dimensions must agree.
Dr. R.N. Patel, email: 85
Another useful operator is transpose operator ('). For example, a column vector
becomes a row vector after the transpose operation. The transpose of a matrix A is

>> A=[1;3;5] % creates a column matrix A
A =
>> B=A' % the ' operator is used to get the row vector
B =
1 3 5

>> C = [1 2; 3 4; 5 6] % Create a 32 matrix
C =
1 2
3 4
5 6
>> D = C' % D is 23 matrix
D =
1 3 5
2 4 6
Dr. R.N. Patel, email: 86
In case of matrices of complex numbers, the transpose operator ' gives conjugated
transpose. To get non-conjugated transpose, .' operator is used.

>> A=[2+3i, 2-3i, 1; 1+i , 1-i , 0]
A =
2.0000 + 3.0000i 2.0000 - 3.0000i 1.0000
1.0000 + 1.0000i 1.0000 - 1.0000i 0
>> A' %gives conjugate transpose
ans =
2.0000 - 3.0000i 1.0000 - 1.0000i
2.0000 + 3.0000i 1.0000 + 1.0000i
1.0000 0
>> A.' % the dot (.) preceding (') makes it
% a simple (un-conjugated) transpose
ans =
2.0000 + 3.0000i 1.0000 + 1.0000i
2.0000 - 3.0000i 1.0000 - 1.0000i
1.0000 0
Dr. R.N. Patel, email: 87
Matrix Multiplication and Inversion
>> A = [1 2; 3 4]
A =
1 2
3 4
>> B = 2*ones(2)
B =
2 2
2 2
Consider the matrix multiplication AB and BA as shown below:
>> A*B
ans =
6 6
14 14
>> B*A
ans =
8 12
8 12
Dr. R.N. Patel, email: 88
The two special matrix operations supported by MATLAB provide rapid
solutions to simultaneous equations or linear regression problems. These
operations are:

Backslash or left matrix divide \:If A and B are two matrices, A\B is the
matrix division of A into B, which is roughly the same as (Inverse of A)B ,
except it is computed in a different way.
X = A\B is the solution to the equation A*X = B computed by Gaussian
elimination. In other words, using backslash operator, you can quickly
solve many equations.

Slash or right matrix divide /: If A and B are two matrices, A/B is the matrix
division of B into A. A/B is roughly the same as A(Inverse of B).

Dr. R.N. Patel, email: 89
>> A = [1 2; 3 4]
A =
1 2
3 4
>> B = magic(2)
B =
1 3
4 2
>> C = A\B
C =
2.0000 -4.0000
-0.5000 3.5000
Dr. R.N. Patel, email: 90
>> F = A/B
ans =
0.6000 0.1000
1.0000 0.5000
You can verify that A/B is approximately equal to A(Inverse of B) as shown
>> G = inv(B)
-0.2000 0.3000
0.4000 -0.1000
>> H = A*G
H =
0.6000 0.1000
1.0000 0.5000
Dr. R.N. Patel, email: 91
Example: Solving the system of equations
+ 8x
+ 2x
= 26
+ 4x
+ 6x
= 12
+ 2x
+ 4x
= 14

The given system of equation can be written in matrix form as:
A*X = B
Where, X = [x
]' , A and B are given below

>> A = [2 8 2; 3 4 6; 6 2 4], B = [26 12 14]'
A =
2 8 2
3 4 6
6 2 4
B =

Dr. R.N. Patel, email: 92
Example: Solving the system of equations
Method 1:
Since A*X = B, X can be written as follows:
>> X = inv (A)* B % Where inv (A) is inverse of matrix A

This computes the solution as:

X =

Method 2:
You can also get the solution using the backslash operator as shown below:
>> X = A\B
ans =

You can verify the result by substituting X values into system of equations (or by multiplying
the matrices A and X).

Dr. R.N. Patel, email: 93
Array Operators

Most of the operators discussed above (such as *, ^ or /), if preceded by a dot
(.) result in an element by element operation (also known as an array
operation). Accordingly, these operators are known as array operators.

>> X = [1 2 3]
X =
1 2 3
>> Y = [4 5 6]
Y =
4 5 6
>> X .* Y % Element by element multiplication
ans =
4 10 18

>> X * Y
??? Error using ==> *
Inner matrix dimensions must agree.
Dr. R.N. Patel, email: 94
We can also apply array operations on power, slash and backslash operators
as shown below:
Array Power
>> D = X.^Y % Array power
D =
1 32 729
The element D(1) is formed above by X(1)^Y(1). Similarly, all the other
elements can be computed.
Array division
>> E= X./Y % Element by element division
E =
0.2500 0.4000 0.5000
The element E(1) is formed in above command by X(1)/Y(1). All the other
elements can be computed in a similar manner.
Dr. R.N. Patel, email: 95

Array Inverse division
>> F = X.\Y
F =
4.0000 2.5000 2.0000
The element F(1) is formed by Y(1) divided by X(1). All the other elements can be
computed in a similar manner.

You can even divide a scalar by each element of a vector or a matrix as shown
>> G = 12./Y
G =
3.0000 2.4000 2.0000

The element G(1) is computed as 12/Y(1). The other elements can be computed in a
similar manner.
Dr. R.N. Patel, email: 96
The use of . Element
K= x^2
??? Error using ==> mpower Matrix must be square.
??? Error using ==> mtimes Inner matrix dimensions must agree.
A = [1 2 3; 5 1 4; 3 2 1]
A =
1 2 3
5 1 4
3 2 -1
y = A(3 ,:)

3 4 -1
b = x .* y

3 8 -3
c = x . / y

0.33 0.5 -3
d = x .^2

1 4 9
x = A(1,:)

1 2 3
Dr. R.N. Patel, email:
Relational Operators
The Boolean (or relational) operators are used for decision-making. A positive
number (usually 1) represents TRUE and zero represents FALSE. For

>> a=3; b=7;

>> c = b>a
c =
>> d = a>b
d =
Dr. R.N. Patel, email: 98
The relational operators in MATLAB are given in the table below:

Dr. R.N. Patel, email: 99
When matrices are used with the relational operators, the size of the
matrices should be the same. The comparison is made on an element
by element basis (an array operation) for matrices and vectors.
Consider the following examples:

>> [1 2]==[1 3]
ans =
1 0

>> [1 2 3; 3 5 6]>[0 4 3; 1 3 7]
ans =
1 0 0
1 1 0

>> (1+10i) < (2+i)
ans =
Dr. R.N. Patel, email: 100
In the last example, the first complex number proves to be smaller than the
second number. The reason is that any logical operator in MATLAB
compares only the real parts in case of complex numbers. If the
comparison of the magnitude is required, it should be :

>> abs(1+10i) < abs(2+i)
ans =

The relational operators can also be used with the string data as shown in the
following command:

>> 'raman'=='samir'
ans =
0 1 1 0 0

Such comparisons can be useful in arranging the names in alphabetical order,
verifying login and password and many other similar purposes.
Dr. R.N. Patel, email: 101
Logical Operators:

The relational operators may be combined by logical operators, which are:
Symbol Operation
& And
| Or
~ Not

The order of precedence for these logical operators is as follows:

~ & |

>> 8>6&'c'>'b'
ans =
>> 2>3|(1+2i)<2
ans =
Dr. R.N. Patel, email: 102
The relation operator can also be applied to vectors or matrices of equal
dimensions as shown in the example below:
>> A = [1 4 9];
>> B = [2 2 5];
>> C = [0 5 2];
>> d = A>B & A>C
d =
0 0 1
The expression d = A>B & A>C is evaluated by taking and of the two
vector A>B and A>C, both of which are shown below:
>> A>B
ans =
0 1 1
>> A>C
ans =
1 0 1
Dr. R.N. Patel, email: 103
Properties of a Matrix

Some of the important numerical values associated with a matrix are its size,
determinant value and rank.

>> A = [3*eye(2), 2*ones(2); 2*ones(2), 3*eye(2)]
A =
3 0 2 2
0 3 2 2
2 2 3 0
2 2 0 3
>> size(A) % is the pair of numbers [m n]
% m is number of rows
% n is columns
ans =
4 4
>> det(A) % is the determinant (A must be a square matrix)
ans =
>> rank(A) % is the rank of matrix A
ans =
Dr. R.N. Patel, email: 104
Replicating Data to Form a Matrix

MATLAB provides two functions that can be used to create matrices by
replicating a scalar, a column vector, a row vector, or a matrix some
specified number of times. These functions are useful in 2-D and 3-D
plots of a function. These two functions are: repmat and meshgrid.
The general syntax for repmat is:
>> repmat (x,r,c)
Where x can be a scalar, a vector or a matrix. The function repmat will
produce r c tiling of copies of x. Consider the following example:
>> P = repmat (2.5, 2, 3)
The above command results in the following output:
p =
2.5000 2.5000 2.5000
2.5000 2.5000 2.5000
Dr. R.N. Patel, email: 105
>> R = repmat ([1, 2]', 2, 3) % the symbol ' indicates
% transpose of vector
R =
1 1 1
2 2 2
1 1 1
2 2 2

The resultant matrix R is tiling of the vector [1, 2]' into two rows and three
columns. You can also tile a matrix into any number of rows and columns
as shown in the example below:

>> s = repmat ([3 7; 5 9], 2, 3) % produces (23) tiles of given
% matrix [3 7; 5 9]
s =
3 7 3 7 3 7
5 9 5 9 5 9
3 7 3 7 3 7
5 9 5 9 5 9
Dr. R.N. Patel, email: 106
Another useful command for preparing vectors for plotting is the meshgrid
command. [X,Y] = meshgrid (x,y),
The rows of the output matrix X are copies of the vector x and the columns of the
output matrix Y are copies of the vector y.
>> x = [1 2 3 4];
>> y = [5 6 7 8];
>> [X Y] = meshgrid(x,y)
X =
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
Y =
5 5 5 5
6 6 6 6
7 7 7 7
8 8 8 8
Both X and Y are matrices of same size (44) and they make a proper combination of
coordinates to be used for plotting purposes.

Dr. R.N. Patel, email: 107
Thank You !

For your Patience and Attention
Dr. R.N. Patel, email: 108
MATLAB Graphics and Plotting
Dr. R.N. Patel, email:
3.1 Introduction
3.2 2-Dimensional Plots
3.3 Plot Aesthetics
3.3.1 Changing the Axis
3.3.2 Adding Text
3.4 Multiple Plots
3.4.1 Using a Single plot Command
3.4.2 Using Multiple plot Commands
3.5 Sub-plotting
3.6 Some Other Useful 2-D Plots
3.7 Advanced Concepts on Plot Annotation and Labeling
3.7.1 Using Handle Graphics
3.7.2 An Easier Way to Plot Editing
3.8 3-D Graphics
3.9 Function Plotters`
Dr. R.N. Patel, email: 110
2-Dimensional Plots
One of the most important functions in MATLAB is the plot
function and it is also one of the easiest functions to learn
and use. The basic format of the function in MATLAB for a
linear plot is:
plots the elements of vector (or matrix) X on the horizontal
axis of a figure, and the elements of vector (or matrix) Y on
the vertical axis of the figure.
Dr. R.N. Patel, email: 111
Given a linear formula:
y = 3x+7
Create an m-file for plot of y versus x.

The following lines of code create the desired plot:
X = 0:0.1:10; % X takes the values from 1 to 10 in
% interval of 0.1
Y = 3*X + 7; % Y generates an array of values for
% each value of X
plot(X,Y) % plots Y values versus their X
% counterparts
Dr. R.N. Patel, email: 112
The color and point marker can be changed on a plot by adding a third
parameter in single quotes to the plot command. For example, to plot the
above function as a red, dotted line, the code should be changed to:
X = 0:0.1:10;
Y = 3*X + 7;
Note that the third argument has r standing for red color and : for dotted

A user can select any combination of color, marker style and line style and
place it in place of string style in the following command:
plot(X,Y, style)
Dr. R.N. Patel, email: 113
>> X = 0:10;
>> Y = 3*X+7;
>> plot (X,Y, 'mp-.')

This code plots a magenta (denoted by m in the
argument) dash-dot line (denoted by -. in the
argument) with a pentagram marker at each data
point (denoted by p in the argument)
Dr. R.N. Patel, email: 114
Plot Aesthetics
Having obtained a certain plot for the given data, its proper
labeling and annotation is extremely important, otherwise
it becomes difficult to extract any useful information from
the given plot.

Changing the Axis
One of the important features in clarity of a plot is proper
selection of axes ranges. For instance, in order to plot the
function y=exp(5t)-1, where y is the function of time t,
enter the following commands at MATLAB prompt:
>> T = 0:0.01:5;
>> Y = exp(5*T)-1;
>> plot(T,Y)
Dr. R.N. Patel, email: 115
It is quite difficult to visualize the nature of the function for the
time interval 0 to 1 sec. One option is to go back and write the
code again for t=0 to t=1 sec. However, the better and simpler
way is to use the axis command.

>> axis([0, 1, 0, 50])

General format:
axis([xmin, xmax, ymin, ymax]);

Here (xmin, xmax) and (ymin, ymax) specify the x and y axis
ranges, respectively.
Dr. R.N. Patel, email: 116
Adding Text

A title will be placed in the center and above the plot figure with the
>> title('title string')
The x-axis is labeled with the command:
>> xlabel('x-axis string')
Similarly, the y-axis is labeled with the following command:
>> ylabel('y-axis string')

Consider the previous example of plotting the function y=exp(5t-1).

title('an exponential plot')
xlabel('time (sec)')
ylabel('the function values, specified units')
The plot appears as shown
Dr. R.N. Patel, email: 117
any other text can be put at any location inside the plot in one
of the two ways:
- Using the text command: This involves knowing the exact
coordinates of the point where you want the text string. The
syntax is:

- Using the gtext command: The syntax of this command is:

After issuing this command at the command prompt, you should
move the cross-hair to the desired location with the mouse,
and click at the position you want the text string to be placed.
Dr. R.N. Patel, email: 118
Following is the complete m-file to summarize what you learnt
so far about the plot aesthetics:
% Learning Plot Aesthetics
T=0:0.01:5; % take the time range of 0 to 5 sec.Y=exp(5*T)-1;
% y is a function of time t
plot(T,Y) % plots y for given time range
axis([0, 1, 0, 50]) % set the axes limits for better clarity
title('an exponential plot') % this gives a title to your plot
xlabel('time (sec)') % label for x-axis (must be a string .)
ylabel('the function values, specified units') % label for y-axis
gtext('labeling at any location') % put a label anywhere
% within the plot
Execute the above m-file at your MATLAB window by setting proper path and
typing the following command:
>> add_text
Dr. R.N. Patel, email: 119
Multiple Plots
Many times you may have to plot many functions in different
figures or multiple functions in the same figure. For example,
an electrical engineer may be interested to plot the current
drawn and the power consumed by a device as a function of
time on the same figure. The following piece of code is an
initial attempt to create many plots together:

>> X = linspace(0,2*pi,50);
>> Y = sin(X); % Y is the first function of X
>> Z = cos(X); % Z is the second function of X
>> W = tan(X); % W is the third function of X
Let us plot the data Y versus X:
>> plot (X,Y)
Dr. R.N. Patel, email: 120
Next you can plot data Z versus X using the following command:
>> plot (X,Z)

If you desire each plot to be displayed in a separate figure window:
>> plot (X,Y)
>> figure % this command will create a new figure window
% to be used for your next plot
>> plot (X,Z)

After entering the above code, you will have the plots in two different figure
windows. Each time you issue the figure command, it creates a new figure
window which can be used for plotting a new dataset. The most recent
becomes the current figure window.

All the subsequent plot editing commands (such as changing the axes and
adding texts) are applicable to this current figure window.

Dr. R.N. Patel, email: 121
For example, the command below labels the figure depicting

>> plot (X,Y)
>> figure
>> plot (X,Z)
>> title(Plot of z=cos(x));
>> xlabel(angle x);
>> ylabel(Z);

Suppose you want to label or edit plot(X,Y) figure in the above example. You
can do so by clicking over plot(X,Y) figure with your mouse button. This
makes the desired window as your current figure window
Dr. R.N. Patel, email: 122
You can close any window, either by using the mouse button, or by issuing the
following command:
>> close % This command will close the
% window, which is
% acting as the current figure window
>> close all % closes all the open figure windows

If you like to just clear the plot and want to use the same figure window for
another plot then, then the following command is helpful:
>> clf % clears the plot from the current figure window, while
% keeps the window open for the next plot
Dr. R.N. Patel, email: 123
Multiple Plots on a Window
In order to plot more than one function on one figure window, there are two
ways listed below:
- Using single plot command: The first one is to use only one plot command
with the parameters for all the functions to be plotted.
- Using multiple plot commands: The second one is to use multiple plot
commands but use hold on command to plot all the curves on the same
figure window.

The following example illustrates the usage of single plot command. The
following M-file can be used to plot a sine wave and a cosine wave on the
same set of axes, using different color and point markers:
X = linspace(0,2*pi,50); % Take 50 samples for x in range 0 to 2*pi
Y = sin(X); Z = cos(X);
plot(X,Y,'r', X,Z,'bx') % could be more than two plots as well
legend ('sin x', 'cos x', 0) % This is for labeling the two curves
Dr. R.N. Patel, email: 124
The legend function used in above code creates the legends for
the plot. The basic form is:
legend ( string-1, string-2, , pos)

Where, string-1, string-2, and so forth are the labels associated
with the plotted functions, and pos is an integer specifying
where to place the legend. For example, 0 in the previous
case indicates automatic "best" placement for the Legends.
Dr. R.N. Patel, email: 125
You can generate identical plot using multiple plot commands. You also use
hold on and hold off commands. After the use of a hold on command,
all subsequent plots will be generated over the same figure window,
without erasing the previous plot, until the hold off command is

-------------------------------------- mult_plot2.m-----------------------------------
X = linspace(0,2*pi,50); % Choose 50 samples in range 0 to 2*pi
Y = sin(X); plot(X,Y,'r') % the figure would be created at this
% point with y versus x curve
Z = cos(X);
hold on % holds the figure window so as to plot the
% subsequent plots on the same set of axes
plot(X, Z,'bx') % z versus x curve is added to the figure
hold off % looses the control over current figure. Any
% subsequent plot command will create a new figure
Dr. R.N. Patel, email: 126

Sometimes creating a single plot for several functions is not
practical due to different scales and units of the functions.
In Science and Engineering applications, often it is desirable
to visualize many functions together, and subplot command
can easily serve the purpose in place of having many
different plots and trying to bring them together. The
following example illustrates the difficulty in plotting two
dissimilar functions.
Dr. R.N. Patel, email: 127
The average yearly rainfall and production of rice in a particular
state is given by the following table for 7 consecutive years:

To visualize the trend of rainfall and its effect on production of
the crop, it is desired to plot the given data over a single
window. MATLAB does this is as follows:
Year 1997 1998 1999 2000 2001 2002 2003
Yearly Rainfall
(in cms)
64.5 72.1 68.7 67.9 68.3 62.5 67.5
Rice Production
(in million tonnes)
4.47 4.52 4.95 5.12 5.10 4.37 5.13

Dr. R.N. Patel, email: 128
--------------------------------------- mult_plot3.m ---------------------------------
% m-file for rainfall and rice production data
years = [1997 1998 1999 2000 2001 2002 2003];
rain = [64.5 72.1 68.7 67.9 68.3 62.5 67.5];
crop = [4.47 4.52 4.95 5.12 5.10 4.37 5.13];

% above three variables take the respective data in vector forms.

plot(years,rain,'r', years,crop,'bx-.') % plots the given yearly
% data for rain and crop yield on the same figure window

xlabel('Year') % on the x axis is year, while y-axis is common to
% both rain and production data; the following
% legend differentiates the two curves

legend('average rainfall (cms)','crop yield (million tonnes)',0)
Dr. R.N. Patel, email: 129
In situations like above Example, where more than one functions is required
to be plotted on a figure, the subplot command is used. The subplot
command allows you to separate the figure into as many plots as desired,
and arrange them all in one figure. The general format of this command is

splits the figure into a matrix of m rows and n columns, thereby creating
mn subplots on one figure window. The variable p creates a handle for
the current figure/plot window, and hence any subsequent plot editing
commands apply to this. For example, subplot(2,2,1) will split the window
space in 22 partitions and the figure handle is set to the (first row, first
column) partition. Any subsequent plot command will create a plot in this
Dr. R.N. Patel, email: 130
The following MATLAB code uses subplot command for the rainfall and rice
production data given in Example 1:

------------------------- sub_plot1.m ---------------------------
years = [1997 1998 1999 2000 2001 2002 2003];
rain = [64.5 72.1 68.7 67.9 68.3 62.5 67.5];
crop = [4.47 4.52 4.95 5.12 5.10 4.37 5.13];
% creating subplots for rainfall and rice production data
subplot (2,1,1) % splits the figure into a 21 window,
% you can access the first partition for plotting
plot(years,rain,'r') % plot for the rain data
xlabel('Years') % x-label for the current plot
ylabel('average rainfall (cms)') % y-label for the current plot
subplot (2,1,2) % now access the second portion of a (2,1) window
plot(years,crop,'bx-.') % plot for the crop data
xlabel('Years') % x-label for the current plot
ylabel('crop yield (million tonnes)') % y-label for the current plot

Dr. R.N. Patel, email: 131
--------------------------- ------ sub_plot2.m ---------------------
X = linspace(0,2*pi,50); % Choose 50 samples in range 0 to 2*pi
Y = sin(X); Z = cos(X); W = tan(X);
subplot(2,2,1) % Sets the axis handle for the next plot command
plot(X,Y) % Plot Y versus X curve at the current axis handle
subplot(2,2,2) % Sets the axis handle for the next plot command
plot(X,Z) % Plot Z versus X curve at the current axis handle
Dr. R.N. Patel, email: 132
The plot is shown in Figure. There are only three plots though 2 2 partitions
of 4 subplots were created. If you do not fill all of the subplots you have
created, MATLAB leaves those subplots as empty space. You could have
easily created another plot using the line subplot(2,2,4) command.

A plot command issued after a subplot command places the new plot in
whichever subplot position was last used, erasing the plot that was
previously in it. For example, in the m-file above, if a plot command was
issued later in the m-file, it would be plotted in the third position in the
subplot, erasing the tangent plot. To solve this problem, the figure should
be cleared (using clf), or a new figure should be specified (using figure
command). If you want to return to a certain subplot (say n) for further
editing, this could be accomplished by using the command subplot(l,m,n).
Dr. R.N. Patel, email: 133
Plot the rainfall and crop production data given in Example 1 using
plotyy command.
MATLAB code using plotyy:
------------------------ yyplot.m ------------------------------------
% using plotyy command for the data with distinct ranges
years = [1997 1998 1999 2000 2001 2002 2003];
rain = [64.5 72.1 68.7 67.9 68.3 62.5 67.5];
crop = [4.47 4.52 4.95 5.12 5.10 4.37 5.13];
plotyy(years,rain, years,crop)% chooses left hand y-axis for average
% rainfall data and right hand y-axis
% for crop yield data
xlabel('Years') % on common x axis is Years
gtext('average rainfall (cms)') % to label the first curve
gtext ('crop yield(million tonnes)') % label for the second curve
Dr. R.N. Patel, email: 134
Some Other Useful 2-D Plots:

The plot command gives you a linear plot. Linear plots are most
useful and frequently used, yet there are other important
plot types such as pie-charts, bar-charts, and logarithmic
plots. MATLAB provides an easy way to create many such
plot types. Following are a few examples on some of the
plot types.

Dr. R.N. Patel, email: 135
Plotting a pie chart
The rough estimate of a typical households monthly budget is
given in the table below. Plot a Pie chart for the same and
emphasize the second slice in the chart.
Budget Component Total Expenditure (in Rs.)
Childrens Education
Medical Care
5, 000
8, 000
2, 000
5, 000
1, 500
2, 500
Grand Total (Rs.) 24, 000

Dr. R.N. Patel, email: 136
Following M-file plots a pie-chart:
-------------------------------------- pie_chart.m --------------------------
%A typical pie-chart
x = [5000, 8000, 2000, 5000, 1500, 2500]; % vector x
% corresponds to the given data set in the problem
labels = {'Essentials', 'Luxuries', 'Entertainment', 'Childrens ...
Education', 'Medical Care', 'Savings'};
% give labels sequentially to your data within a { }
explode = [0 1 0 0 0 0]; % vector explode is set to 1, for the
% slice that you want to highlight
pie (x, explode, labels) % plot the pie chart for the given data
title ('a typical Households monthly budget')
% gives a title for the given chart
Dr. R.N. Patel, email: 137
Drawing a histogram
Following are the marks obtained by 70 students of a class in a
certain subject with maximum marks equal to 50:

marks = [32, 45, 7, 38, 40, 15, 5, 26, 0, 11, 40, 2, 18, 8, 31, 4, 27,
7, 0, 15, 12, 35, 28, 46, 9, 29, 10, 34, 2, 7, 5, 17, 2, 8, 35, 30,
11, 36, 47, 19, 16, 0, 18, 16, 14, 2, 38, 41, 42, 17, 45, 28, 48,
20, 7, 21, 8, 5, 28, 13, 22, 27, 41, 40, 36, 29, 29, 31, 34, 48]

Arrange this data to plot the marks as a histogram of 7 bins.
Analyze the total number of students falling under different
marks intervals. Also draw an approximate plot showing how
the frequency of students varies with increasing marks.
Dr. R.N. Patel, email: 138
Here are the simple commands for the desired plot (assuming that vector
marks have already been entered as given above) :
------------------------- histogram.m -------------------------
hist (marks, 7) % plots the histogram for the given data with 7 bins
title('Marks Distribution in Subject ABC')
xlabel('Marks Ranges')
ylabel('No. of Students')
hold on % hold the plot to draw the frequency curve
[n, x] = hist (marks, 7) % n gives the frequency falling under
% each bin and x is the vector containing
% the location of bin centers.
plot (x, n, 'md--') % plots a dashed graph on the same plot,
% showing the frequency curve.
hold off
Dr. R.N. Patel, email: 139
Advanced Concepts on Plot
Annotation and Labeling
Dr. R.N. Patel, email: 140
Using Handle Graphics:
Whenever a plot or multiple plots are created, MATLAB defines a handle to
all the important objects of the plot, such as the axes, the labels, and
the curve itself. A handle can be thought of as an identity or an
address of a particular object within a plot. MATLAB assigns an
address to each object and if you provide that address, MATLAB can
also retrieve a list of the current properties of that object. You can
then change any desired property and feature of the object.
Some of the important MATLAB functions on handles are listed below:
gca: get handle to current axes
gcf: get handle to current figure
gco: get handle to current object
Dr. R.N. Patel, email: 141
If you want to modify the properties of the axes of the current
plot, you must first get the handle of the axes as shown
h1 = gca % the variable name h1 gets the handle of
% the axes of the current plot

The next step is to know the properties of the axes. You can
know the properties of the axes using get command as
shown in the code below:
>> figure % creates a new figure window
>> h1 = gca % gets the handle to the axes
>> get(h1) % get the list of all the properties of
% the object with handle h1.
Dr. R.N. Patel, email: 142
Next, you can change any of the enlisted properties such as FontName using set
command. The format of set command is as follows:
You can also set multiple property values with a single statement using the
following format of set command:
The following example illustrates the use of set command:
>> figure
>> h1 = gca;
>> set(h1, 'FontSize',12,'FontWeight','bold')
>> plot(2:8, 3:9) % this plot will be with the axes properties in
% previous command
>> set(h1, 'FontSize',20,'FontWeight','bold') % changes the axes
% properties as per the specifications given
Dr. R.N. Patel, email: 143
Example: The process of Carbon dating is that the amount of
time that has passed can be measured with the help of the
following Radio-active decay equation:
= Q
. e
-. t

where, Q
is the amount of radio-active C14 present at present
time, Q
is the initial amount of radio-active C14 and is the
decay constant (0.00012097/year, for C-14).
Write a program to plot the percent of C-14 remaining as a
function of time and indicate the half life period in the curve.
Dr. R.N. Patel, email: 144
The equation can be written as:
t = - 1/ . log
The half life period of C-14 is the time required for the amount of C-14 to become
half of the original amount, i.e., Q
= 0.5Q

The MATLAB code for the given task is written below:
-------------------------------------- C_dating.m -----------------------------------------------
% m-file Program for Carbon Dating
t= 0:100:10000;
lamda= 0.00012097;
q_percent= 100*exp(-lamda.*t);
plot(t, q_percent, 'LineWidth',1)
set(gca, 'LineWidth',1, 'Fontsize',10)
xlabel('\bf\fontsize{10} Time elapsed in years')
ylabel('\bf\fontsize{10} % of C-14 remaining')
Dr. R.N. Patel, email: 145
text(3000,100*exp(-lamda*3000),'\leftarrow Q_t/Q_0 = e^{-\lambda.t}')
hold on
half_life = -1/lamda*log(0.5)
plot (half_life, 50,'s','MarkerEdgeColor','k',...
'MarkerFaceColor',[.49 1 .63],'MarkerSize',8)
line([0 half_life],[50 50],'LineStyle',':','color','k')
line([half_life half_life],[10 50],'LineStyle',':','color','k')
text(100,48,'\it\bf\fontname{courier}\fontsize{10} half life period of C-14')
Dr. R.N. Patel, email: 146
The Plot
0 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000
Time elapsed in years




= e
half life period of C-14
= e
half life period of C-14
Dr. R.N. Patel, email:
LaTeX syntax for Upper and Lower case Greek letters and Mathematical Symbols

Lower case letters
case letters
Mathematical symbols
Symbol Syntax Symbol Syntax Symbol Syntax Symbol Syntax Symbol Syntax
o \alpha \rho I \Gamma } \int \propto
| \beta o \sigma A \Delta \sum \circ
\gamma t \tau A \Lamda ~ \cong \infty
o \delta e \omega H \Pi ~ \sim ' \prime
c \epsilon k \kappa E \Sigma = \neq \leftarrow
q \eta \xi O \Omega > \geq : \Leftarrow
u \theta o o O \Theta s \leq \rightarrow
\lambda u \upsilon \Xi >> \gg | \uparrow
\mu , \zeta T \Upsilon << \ll + \downarrow
v \nu _ \chi u \Phi \pm Z \angle
t \pi \psi + \Psi \times \ \surd
| \phi i \iota \div $ \$
Dr. R.N. Patel, email: 148
An Easier Way to Plot Editing

There is an easier method to edit the plots in a dynamic way
using the Graphical User Interface (GUI) available in the Figure
Window. Take the example of one of the plots that was
created previously.

x = linspace(0,2*pi,50);
y = sin(x); z = cos(x);
plot(x,y,'r', x,z,'bx')
legend ('sinx', 'cosx', 0)
Dr. R.N. Patel, email: 149
3-D Graphics
3-D plots have their own important role in plotting the functions that cannot
be interpreted well in a 2-D plane. If a certain function z depends on the
two variables x and y, in order to know the nature of such a function
over x-y plane, you need a 3-Dimensional plot.
MATLAB has several built-in functions for plotting three-dimensional objects.
to plot curves in space (plot3),
mesh surfaces (mesh),
surfaces (surf) and
two functions for plotting special surfaces, sphere and cylinder
use MATLAB help on 3-D plots (>> help graph3d), to find more information on
certain plot features.
Dr. R.N. Patel, email: 150
Following is an illustration of a 3-D plot:

An object moves over x-y plane with the following functions of
time t:
x = t*cos(t),
y = t*sin(t),
Find the trajectory of the objects movement for the time
(-10 < t < 10 ), taking the time along z-axis.

The m-file for the problem is given below:
Dr. R.N. Patel, email: 151
------------------------------------ plot3D1.m ----------------------------
%trajectory of the object with time t; t is along z-axis
t = -10*pi:pi/100:10*pi;
x = t.*cos(t); % note that this is an array multiplication; will
% require a dot operator preceding *
y = t.*sin(t);
h = plot3(x,y,t); % plots x, y and t in a 3-D space
title('Curve u(t) = < t*cos(t), t*sin(t), t >') % curve title
grid % sets the grid lines to the plot.
%grid off remove them
Dr. R.N. Patel, email: 152
Now execute the following:
>> sphere(30);
>> figure

>> cylinder([1 0])
>> title('Unit cone')
Dr. R.N. Patel, email: 153
Function Plotters

fplot(function, LIMS)

% plots the function FUN between the x-axis
% limits specified by LIMS = [xmin xmax].
% Use of LIMS = [xmin xmax ymin ymax], also controls the y-axis
% limits. The function must be supplied within the quotes.

Let us take the simple exponential equation ( y = e
-1 ).

>> fplot('exp(5*t)-1', [0 1 0 50]) % note that in place of t, it
% could be x or y or any other single variable as well.

Dr. R.N. Patel, email: 154
Suppose, there is function in x and y as:
+ y
- 4*x*y + 1/5 = 0
If you are asked to plot this expression using fplot, you will have tough time
in writing it in the form of y = f(x). In order to see that dependency of
y over x for the range {-3 < x < 3 }, type the following at MATLAB

>> ezplot('x^2 + y^2 - 4*x*y + 1/5',[-3,3])
Dr. R.N. Patel, email: 155
Thank You !
Dr. R.N. Patel, email: 156
Control Structures, Loops, and Functions
Dr. R.N. Patel, email: 157
4.1 Introduction
4.2 Conditional Statements
4.3 Loops
4.4 Nested Loops
4.5 Breaking Control Structures
(break and continue)
4.6 Functions
Dr. R.N. Patel, email: 158
There are two conditional constructs provided by MATLAB: the if construct
and the switch construct.
>> marks = 57; % the variable has to be assigned a value before we
% can use it in an expression;
>> if (marks>35)
end % it wont display anything unless you put an end
% there
Dr. R.N. Patel, email: 159
Consider another example as follows:
>> a = 3;b=2;
>> if (a>b) disp('a is larger'); disp('b is smaller'); end; c=5

MATLAB responds as follows:
a is larger
b is smaller
c =
Dr. R.N. Patel, email: 160
Example 4.1
Assign different grades to students based on the
conditions given below, using an if-else construction:

Marks: above 85 70 to 84 55 to 69 40 to 54 below 40
Grade: A B C D F

Dr. R.N. Patel, email: 161
------------------------------------- grading.m------------------------------------------------
% script file to display the grade based on subject marks
marks = input('Enter the marks :') % invokes the user to enter the
% marks at the command prompt
if (marks >= 85)
disp('Grade: A');
elseif (marks >= 70)
disp('Grade: B');
elseif (marks >= 55)
disp('Grade: C');
elseif (marks >= 40)
disp('Grade: D');
disp('Grade: F');
disp('You have to take the course again');

Dr. R.N. Patel, email: 162
if (logical expression)
switch switch_expr
case case_expr1
case case_expr2
case case_expr3
In switch-case construction the switch_expr is a variable name, whereas the
case-expressions are either numeric or character or numeric constants. Unlike
other programming languages, the case sections dont require any break
statements, since the switch statements here do not follow the fall through
principle. Using end statement is a must at the termination of every if-else or
switch-case construction.

Dr. R.N. Patel, email:
% A switch-case example

day = input('Enter a number for the day ( 1 to 7)')
disp ('The day is :' )

switch (day)
case 1
disp ('Monday')
case 2
disp ('Tuesday')
case 3
disp ('Wednesday')
case 4
disp ('Thursday')
case 5
disp ('Friday')
case 6
disp ('Saturday')
case 7
disp ('Sunday')
disp ('Not a valid entry for the day')
Dr. R.N. Patel, email: 164
The general form and syntax of these loops are as
for variable = init_value: step : final_value
while (expression)
Note that in the absence of the step variable in for
loop, the step size has the default value of one. Like
the conditional structures, the loops also require an
end statement indicating the termination of the loop.
Dr. R.N. Patel, email:
% factorial using a for loop
n = input ('input the number : ');
fact_n = n;
for i = 1: n-1
fact_n = fact_n*i;
disp ( 'factorial of the number is :'),
disp (fact_n);
Dr. R.N. Patel, email: 166
Ex4.2: factorial using a while loop
----------------------------------------- looping-2.m ---------------------------------
% factorial using a while loop
n = input ('input the number : ');
fact_n = n; i = 1;
while i <= (n-1)
fact_n = fact_n * i;
i = i+1;
disp ( 'factorial of the number is :'), disp (fact_n);

Dr. R.N. Patel, email: 167
Nested Loops
% factorial for numbers using a nested loop structure
% breaking the control for a negative number
choice = 'y';
while(choice ~= 'n')
n = input ('input the number : ');
if (n < 0)
disp ('Invalid input for a factorial')
break; % transfers the control to the end of the loop
fact_n = n;
for i = 1: n-1
fact_n = fact_n*i;
disp ( 'factorial of the number is :'), disp (fact_n);
c = input ('do you want to find the factorial for another number? (y/n): ', 's');
choice = lower (c);
Dr. R.N. Patel, email: 168
Breaking a Loop
BREAK terminates the execution of FOR and
WHILE loops.

In nested loops, BREAK exits from the
innermost loop only.

BREAK is not defined outside of a FOR or
WHILE loop.
Dr. R.N. Patel, email: 169
Continuing a Loop
CONTINUE passes control to the next iteration
of FOR or WHILE loop in which it appears,
skipping any remaining statements in the
body of the FOR or WHILE loop.

In nested loops, CONTINUE passes control to
the next iteration of FOR or WHILE loop
enclosing it.
Dr. R.N. Patel, email: 170
Example 4.3
The exponential power of x is approximated by the
following infinite series:
= 1+ x + (x
/ 2!) + (x
/ 3!) + (x
/ 4!) +

Find out how many terms will be sufficient in the right
hand side of the above expression to ensue that the
result is within the 5% error of the exact value.
Assume x has a value of 5.

Dr. R.N. Patel, email: 171
--------------------------------------- exp_power.m ---------------------------------------------
% computing the exponential power with a series
x = 5;
exact = exp (x); %computes the exact value
n = 1; % n is number of terms
sum_terms = 1; % stores the sum for n terms
error = (exact - sum_terms)*100/exact; % percentage error value

while (error > 5)
n = n + 1;
next_term = power (x, n)/factorial (n);
sum_terms = sum_terms + next_term;
error = (exact - sum_terms)*100/exact;

disp ('the exact value = '), disp (exact)
disp ('computed value = '), disp (sum_terms)
disp ('no. of terms required = '), disp (n)

Dr. R.N. Patel, email: 172

Scripts and Functions

Dr. R.N. Patel, email: 173
M-files can be scripts that simply execute a series of MATLAB
statements, or they can be functions that also accept
arguments and produce output. Functions in MATLAB are
like functions in C, subroutines in FORTRAN and BASIC, and
procedures in PASCAL. They are building blocks of larger
programs. When a large task is broken into smaller
functions, it is easier to understand, debug and modify the
Dr. R.N. Patel, email: 174
------------------- sq_root.m -----------------------
function output = sq_root(x)
% Computes the square root of absolute value of x
if (x<0)
output = sqrt(x);
Observe the following commands:
>> x = -3;
>> y = sq_root(x)
y = 1.7321
>> x
x = -3
Dr. R.N. Patel, email: 175
Several things can be noticed from this example. The first line in a function file must
begin with a function definition line that has a list of input and outputs. This line
distinguishes a function M-file from a script M-file. The syntax of first line of a
function M-file is as follows:
function [output_variables] = function_name(input_variables);

Note that the output variables are enclosed in square brackets except when there is a
single output, while the input variables must be enclosed with parentheses. If
there is no output, leave the output blank as shown here:
function function_name (input_variables);

The function_name must be the same as the filename in which it is saved (with the .m
extension). Generally MATLAB editor recognizes from the presence of a function
header that this is going to be a function M-file, and so when asked to save, it
automatically suggests the name for the file as the main function name.
Dr. R.N. Patel, email: 176
Functions in MATLAB can receive multiple arguments of scalar,
vector or other types and return multiple output variables. For
instance, the function below accepts three input arguments, and
returns three outputs.

Example: The formulas below enable us to convert a 3D point
representation from Cartesian coordinates (x,y,z) to cylindrical
coordinates (r,, zcyl):

2 2
r x y = +
tan ( )

zcyl z =
Dr. R.N. Patel, email: 177
The following function converts Cartesian coordinates to
cylindrical coordinates. The function should be saved as
cylindrical.m in your working directory.

------------------- cylindrical.m ------------------------
function [r,theta,zcyl] = cylindrical(x,y,z)
% Converts Cartesian coord. to cylindrical coord.
r = sqrt( x.*x + y.*y );
theta = atan( y ./ x);
zcyl = z;
Dr. R.N. Patel, email: 178
calling cylindrical function from the command prompt:
>> [r,t,z]=cylindrical(10,10,20)
r = 14.1421
t = 0.7854
z = 20
>> cylindrical(10,10,20)
ans =
% In this case since it was not specified which variables
% collect the outputs, therefore the default variable ans
% collected the first output variable.
Dr. R.N. Patel, email: 179
>> a=1:5
a =
1 2 3 4 5
>> b=2:2:10
b =
2 4 6 8 10
>> c=a.*a
c =
1 4 9 16 25
>> [m,n,p] = cylindrical (a,b,c)
m =
2.2361 4.4721 6.7082 8.9443 11.1803
n =
1.1071 1.1071 1.1071 1.1071 1.1071
p =
1 4 9 16 25
Dr. R.N. Patel, email: 180
The vector A contains positive and negative integer
values. To compute logarithm of A, it is desired to
separate the non-positive elements, and the
logarithm of these elements should be assigned a
value of -1. The following script, log_positive.m does
this task:
Dr. R.N. Patel, email: 181
------------------------ log_positive.m -----------------------
function Y = log_positive(X) Function Definition line
% Return log of positive elements in Y H1 Line
% X is an input vector of integers Help Text (comments)
% Example: Y = log_positive([1 2 -1])

disp('In function func_log_positive...');
n = length(X);

for i = 1:n
if X(i)<=0
Y(i) = -1; Function Body
Y(i) = log10(X(i));
disp('Finished executing func_log_positive...');

Dr. R.N. Patel, email: 182
Variable Number of Arguments
A function may choose to accept/return a variable number of
arguments/outputs depending upon the situation. Many
MATLAB functions support passing variable number of input
arguments and output arguments. For example, the function
can be called with as few as two or as many as seven input
Dr. R.N. Patel, email: 183
Consider the following function which calculates the mean and standard
deviation of an input vector.
-------------------------- stat.m ---------------------------
function [mean, std] = stat(x)
%Calculates the mean and standard deviation
% of the input vector x
n = length(x);
mean = sum(x)/n;
if (nargout==2)
disp('Computing Std. Deviation');
std = sqrt(sum((x-mean).^2/n));
Dr. R.N. Patel, email: 184
When stat is called with one output argument, the mean is
returned and the code for computing standard deviation is
not executed as shown below through the following

>> [a] = stat([1 2 3])
a = 2 % value of mean returned in a

When stat is called with two output arguments, the mean and
standard deviation are returned. An example is shown
>> [x y] = stat([1 2 3])
Computing Std. Deviation
x = 2
y = 0.8165
Dr. R.N. Patel, email: 185

When more than one function is present in a function file, the
top function is a normal function, while the ones below it
are subfunctions or internal functions. These subfunction
definitions are like normal functions, but they are only
accessible to the other functions within the same file.

Example: The following example defines a function
that accepts in degrees and computes sine of . Note
that MATLAB trigonometric functions expect their
argument to be in radians.
Dr. R.N. Patel, email: 186
------------------------------ sindegree.m------------------------
function out = sindegree(x) % sindegree is a main function
%% Finds sine of x, where x is in degree
y = convert(x);
out = sin(y);

function a = convert(x) % convert is a subfunction
%% Convert a number in degree to radian
a = (x*pi)/180;

Here is a sample output at command prompt:
>> m=sindegree(45)
m = 0.7071

>> convert(45)
??? Undefined function or variable 'convert'.

Function can be called by any other function or at command line but
subfunctions can only be called by other functions in the same file.
Dr. R.N. Patel, email: 187
Polynomial Functions
In MATLAB, a polynomial is represented by a vector. To create a
polynomial in MATLAB, simply enter each coefficient of the
polynomial into the vector in descending order. For instance,
let us say that you have the following polynomial:

To enter this into MATLAB, just enter it as a vector in the
following manner:
>> f1x = [1 3 -15 -2 9]
f1x = 1 3 -15 -2 9
4 3 2
1( ) 3 15 2 9 f x x x x x = + +
Dr. R.N. Patel, email: 188
if a polynomial is missing any coefficients, one must enter
zeros in the appropriate place in the vector. For example, if ,

then it would be represented in MATLAB as:
y = [1 0 2 0 0]

The value of a polynomial can be evaluated at using the
polyval function. For example, to find the value of the
above polynomial at x=2, use polyval as shown below:

>> z = polyval([1 0 2 0 0],2)
z = 24
4 2
2( ) 2 f x x x = +
Dr. R.N. Patel, email: 189
You can also extract the roots of a polynomial. This is especially useful when
you have a high-order polynomial such as:

Finding the roots is done by using the roots command in MATLAB as
shown below:

>>x = roots([1 3 -15 -2 9])
x =
>> poly(x)
ans =
1.0000 3.0000 -15.0000 -2.0000 9.0000
4 3 2
1( ) 3 15 2 9 f x x x x x = + +
Dr. R.N. Patel, email: 190
Recursive Functions
A function can use either iterative method using loops or the
function can be recursive in nature. Iteration is the process
of repeatedly executing a set of operations until a condition
is met and usually is implemented using for and while
loop. Recursion (or a recurrence relation) in math is the
process of defining a function in terms of a simpler version
of itself. It is the process of successively breaking a problem
into smaller parts where each is a smaller/simpler version of
the previous one until a simple solution is reached. Back-
substitution then leads to the solution for the original
problem. For example, following is a recursive relationship:

( 1) n n n ! = !
Dr. R.N. Patel, email: 191
------------------------------ recr_fact.m -------------------------------
function value = recr_fact(n)
% Recursive version of factorial
% n is positive integer i.e., greater than 0

if (n==1) % Terminating condition
value =1;

value = n*recr_fact(n-1);
% Recursive call bringing argument
% closer to terminating condition

Dr. R.N. Patel, email: 192
Typically a recursive program has three elements and
these are often programmed in an If-then-else
construct. Elements required in a recursive program
A stopping or terminating condition is assigned a
A computation of the value within the loop is
followed by a increment in the value being
computed, which brings it closer to the terminating
Calling the function itself to compute the value of the
function for a reduced input number.

Dr. R.N. Patel, email: 193
Inline Function
It is a powerful command to generate any mathematical
function in symbolic form. For example:

>> f1=inline('x*x')
f1 =
Inline function:
f1(x) = x*x

>> f1(2) % Evaluate f1 at 2
ans =

Dr. R.N. Patel, email: 194
Inline Function

>> f2=inline('sin(t)/cos(t) - 3*(t^3) + 4*t')
f2 =
Inline function:
f2(t) = sin(t)/cos(t) - 3*(t^3) + 4*t

>> f2(1) % Evaluate f2 at 1
ans =

Dr. R.N. Patel, email: 195
Inline Function
You can also create functions of more than one argument with
inline by specifying the names of the input arguments along
with the string expression. For example, the following
function has two input arguments x and y:

>> f3=inline('log( (x+y) / (x-y) )', 'x', 'y')
f3 =
Inline function:
f3(x,y) = log( (x+y) / (x-y) )
>> f3(2,1) % Evaluate at x =2, y = 1
ans =

Dr. R.N. Patel, email: 196
Numerical Integration
Quadrature is a numerical method used to find the area under
the graph of a function, which essentially computes a definite
integral. MATLAB uses various quadrature algorithms to
compute the definite integral:

I =

I = quad (fun, t1, t2) tries to approximate the integral of function
fun from t1 to t2 within an error of 1e-6. Where, fun is a
function handle for either an M-file function or an anonymous
). (
dt t f
Dr. R.N. Patel, email: 197
Example 1: Find the value of the following integral

The given function may either be defined with the help of an
inline function or using a M-file. The following command
evaluates the value of the integral:

>> I = quad (inline('(1+2*x)./(1+x.^2)'), 0, 1)

I =

. 2 1
Dr. R.N. Patel, email: 198
>> tol = [1e-3]; % defines new absolute error tolerance

>> [I, nfev] = quad(@fun2, 0, 1, tol)
% nfev is the number of function evaluations

I =
nfev =

Where, the M-file fun2.m is defined as under:
function y = fun2(x)
% this is a function in x defining the given expression
y = (1+2*x)./(1+x.^2);

Dr. R.N. Patel, email: 199
quadl is another function in MATLAB for evaluation of a
single integral. I = quadl (fun, a, b) approximates the
integral of function fun from a to b, to within an error of
using recursive adaptive Lobatto quadrature.

>> [I, nfev] = quadl (@fun2, 0, 1)

I =
nfev =

Dr. R.N. Patel, email: 200
Double and Triple Integrals
The double and triple integrals can be evaluated using the functions dblquad and
triplequad, which have the following syntax:

I = dblquad(fun,xmin,xmax,ymin,ymax,tol)

I = triplequad(fun,xmin,xmax,ymin,ymax,zmin,zmax,tol)

Example : I =

Solution: Enter the following at the MATLAB command prompt.

>> I = dblquad(inline('exp(-x*y).*sin(x*y)'),-1,1,0,1)
I =

} }
= =

. ) sin( .
x y
dy dx xy e
Dr. R.N. Patel, email: 201
Solution of Nonlinear Algebraic Equations
Gauss-Seidel (GS) Method:
f(x) = x
- 2x
- 5x + 6 = 0

the above equation may be rearranged as:
x = 1/5 (x
- 2x
+ 6 ) = f2 (x)

Thus, the next value of x will be:

= f2(1) = 1/5 ( 6) = 1.2
= f2(1.2) = 1/5 ( (1.2)
+ 6) = 0.9696
the process must continue till we get :

abs( x
- x


the following is the m-file for the GS solution of above equation:

Dr. R.N. Patel, email: 202
% Program for Gauss-Seidel solution of a nonlinear equation
clear all
dx=5; % Iterative Change in variable set to a high value
x=0; % Initial estimate
iter = 0; % Iteration counter
disp('Iter f2 dx x') % Header for results
while (abs(dx) >= 0.001 && iter < 100) % Test convergence
iter = iter + 1; % Current No. of iterations
f2 = (1/5)*(x^3-2*x^2+6);

dx = f2-x; % Iterative Change in variable

x = x + (dx); % Successive approximation
fprintf('%g', iter), disp([f2, dx, x])
% display the iterative solution
Dr. R.N. Patel, email: 203
GS solution for a System of Equations
Consider the system of n-equations, with n unknowns, given as:
, x
, x
,., x
) = c

, x
, x
,., x
) = c

, x
, x
,., x
) = c

, x
, x
,., x
) = c

Solution by GS method will require rearranging the equations in the following form:
= c
+ g
, x
, x
,., x
= c
+ g
, x
, x
,., x
= c
+ g
, x
, x
,., x
= c
+ g
, x
, x
,., x

Dr. R.N. Patel, email: 204
GS solution for a System of Equations

Where, g
, g
, g
are the new functions of x
, x
,., x

Start with a initial set estimate of n variables (x
, x
, x
,., x
) and calculate
the next estimated value of variables with the help of above equations and
continue the process till you get the convergence for all the variables, i.e.,

abs( x

c; where k = 1,2,3,4 n

Dr. R.N. Patel, email: 205
Numerical Solution of Ordinary Differential Equations
Eulers Method for Solution of Differential Equations:

= x
+ A t

) , ( t x f
2 2.5 3 3.5 4
time, t

slope at the initial point
of the interval
= x
+ .
A t
Dr. R.N. Patel, email: 206
Example: A system described by the following equation:

Solve for x = f(t) and plot x for the range of t = 0 to 5 sec.

Solution: The given second order equation must be reduced into two first order
equations to use the Eulers algorithm. Assuming the two variables x
= x

The following gives the MATLAB code for the solution of the equation:

= + x x
x d
, where x = f(t) and Initial conditions are:
x(0) = 0.5 and 0

and x
; the resulting equations will be:

x x
Dr. R.N. Patel, email: 207
% Solution of a Differential Equation using Euler's method
x(1) = 0.5; % specify the initial conditions
x(2) = 0;
delt = 0.01 % specify the time interval
iter = 0; % iteration count
t = 0; % initial value of time
disp('iter time x(1) x(2)')% Header for results
fprintf('%g', iter), disp([t, x(1), x(2)])
for t = delt:delt:5
x(1) = x(1) + x(2)*delt; % calculate x(1)
x(2) = x(2) + (x(1)^2 - x(1))*delt; % calculate x(2)
iter = iter+1;
fprintf('%g', iter), disp([t, x(1), x(2)]) % display the iterative solution
y(iter, :) = [t, x]; % store data in y for ploting
plot(y(:,1), y(:,2)) % plots time versus x (= x(1))
xlabel ('time, t')
ylabel ('var, x')

Dr. R.N. Patel, email: 208
Solution of Differential Equations through ODE
MATLAB provides a good number of ordinary differential equation (ODE) functions,
such as: ode45, ode23, ode113, ode15s, ode23s, ode23t, ode23tb (see help ode
for more details). The solution by these functions essentially requires the
definition of given equation as a separate function in a separate M-file, whose
handle is given as an argument of the ode function. The general syntax for the
solution is:

[t, X] = solver (myfun, tspan, x0, options)

Where myfun is the handle to a user defined function which contains the given
differential equation(s) in the form of only first order differential equations
Dr. R.N. Patel, email: 209
A brief algorithm for the above description can be as below:

1. Break the given set of differential equations into as many first order equations as
necessary. In order to split the higher order equations into first order differential
equations, choose intermediate variables, for example a n
order equation:
0 .......
0 1
= + + + + +

x d
x d
x d
, can be defined by
following n equations:

= = ;
x d
= = ;
x d
= = .
x d
= =

and ) . .......... (
1 3 2 2 1 0 n n
x a x a x a a
a dt
x d

= =

2. Write a user defined function (myfun) that defines all the equations in step 1
and returns the derivatives of the variables x
, x
, , x
as its output.
3. Obtain the initial conditions of the variables x
, x
, , x
and take them in the
corresponding sequence as an array of initial conditions, i.e. x0 = [ x
(0), x
, x
4. Get the time span for solution of the equations; i.e. tspan = [t
, t
] in
5. Execute the command
>> [t, X] = solver (@myfun, tspan, x0) ;
where solver may be anyone of ode functions of MATLAB and X contains the
required solutions for the variables x
, x
, , x
as a matrix with n columns
at specified points of time given by vector t.
Dr. R.N. Patel, email: 210
Old Example: A system described by the following equation:

Solve for x = f(t) and plot x for the range of t = 0 to 5 sec.
= + x x
x d
, where x = f(t) and Initial conditions are:
x(0) = 0.5 and 0

Solution: As discussed earlier, the original second order equation 0
= + x x
x d
, need
to be expressed in terms of two first order equations as:

= and,
x x

Write a function fun1 which returns the values of dx1 and dx2 by taking the arguments
as (t, x); save the function in a m-file (the file name will be the same as the function

function dx = fun1(t,x)
dx = zeros(2,1); % a column vector
dx(1) = x(2); % expression for dx(1)
dx(2) = x(1)^2 - x(1); % expression for x(2)

Dr. R.N. Patel, email: 211
function dx = fun1(t,x)
dx = zeros(2,1); % a column vector
dx(1) = x(2); % expression for dx(1)
dx(2) = x(1)^2 - x(1); % expression for x(2)
Now, lets use the ode function to solve the equation with the same initial conditions
and the time range as in Example 6.11. Here is what you must write over the
MATLAB command prompt:

>> [t,X] = ode45(@fun1,[0 5],[0.5 0])

and see what MATLAB returns. You can plot the solution to compare it with that of old
example by the following commands:

>> plot (t, X(:,1),'r')
>> xlabel ('time, t')
>> ylabel ('var, x')

Dr. R.N. Patel, email: 212
Solve the set of equations:

Initial conditions are y1(0) = 2 and y2(0) = 0

Solution: First write the function file as:

----------------------- fun2.m -------------------------------
function dy = fun2(t,y)
dy = zeros(2,1); % a column vector
dy(1) = y(2);
dy(2) = 1000*(1 - y(1)^2)*y(2) - y(1);

Dr. R.N. Patel, email: 213
Execute the following to see the responses:

>> [T,Y] = ode45(@fun2,[0 3000],[2 0]);

>> [T,Y] = ode15s(@fun2,[0 3000],[2 0]);

>> [T,Y] = ode23t(@fun2,[0 3000],[2 0]);

>> plot(T,Y(:,1),'-o')

Thus, different solvers may be useful for diffrent problems !

Dr. R.N. Patel, email: 214

Dr. R.N. Patel, email: 215
Interpolation is an important operation for data analysis and curve fitting. The need on
interpolation arises when we have a limited number of known data points, yet the
relationship between the coordinates is not known exactly. Now, if you are asked
to get the value of the function (say y-coordinate) for some random value of the
independent variable (say x-coordinate), then we need to interpolate.

The most general form of interpolation is:

= interp1(x,y, x
, method)

Where y is a vector containing a series of values for the corresponding values of x. x
a vector containing the points at which the values y
are desired and method is an
optional string specifying an interpolation method.

Note: If any element of x
is outside the interval spanned by x, the specified
interpolation method is used for extrapolation.

Dr. R.N. Patel, email: 216
Example : Following are two vectors representing the census data of a country from
year 1900 to 2000 with the corresponding population in millions.
year = 1900:10:2000; % indicates the census years
population = [71 87 101 118 127 146 174 198 222 245 264];
Estimate the population in the years 1985 and 2005.


Execute the following statements to get the interpolated values:

>> year = 1900:10:2000; % indicates the census years
population = [71 87 101 118 127 146 174 198 222 245 264];

>> p_1985 = interp1(year,population,1985) % default method is linear
p_1985 =

Dr. R.N. Patel, email: 217
The previous statement estimates the population in the year 1985 with the
default linear interpolation method; whereas the following command
will estimate the population in the year 2005 with the help of cubic
interpolation method:

>> p_2005 = interp1(year,population, 2005, 'cubic')
p_2005 =

Dr. R.N. Patel, email: 218
Multi Dimensional Interpolation
zi=interp2(x, y, z, xi, yi, 'method') performs a two-
dimensional interpolation at points (xi, yi) to get the
corresponding values of zi based on the known set of
data points (x,y,z)

Example A multi-dimensional interpolation example
Generate a coarse mesh plot for the function:
in the range of -10 x 10 and -10 y 10 and
interpolate for z over the finer intervals of x and y using
the 'linear' and the 'cubic' interpolation methods.

Dr. R.N. Patel, email: 219
% Example of a Two-Dimensional interpolation
[x,y] = meshgrid(-10:10); % generates a meshgrid
r = sqrt(x.^2 + y.^2);
z = sin(r)./r; % evaluates the given function
mesh(x,y,z) %coarse mesh plot for the given function
title('a coarse plot for z')
[xi, yi] = meshgrid(-10:.1:10);
% generates a finer meshgrid
zi = interp2(x, y, z, xi, yi, 'bilinear');
% bilinear interpolation figure
mesh(xi, yi, zi), % plot of interpolated values
title('Bilinear interpolation of z')
zi = interp2(x, y, z, xi, yi, 'spline');
% cubic spline interpolation figure
mesh(xi, yi, zi), % plot of interpolated values
title('cubic spline interpolation of z')

Dr. R.N. Patel, email: 220
Curve Fitting
The concept of curve fitting is slightly different from the interpolation. In case of the
interpolation, we try to find the piecewise approximation of the function between
two data points. On the other hand, in curve fitting, the objective is to determine a
single approximate equation for the whole range of given data. The MATLAB
function polyfit gives the most elementary method to curve-fit.

Example : The following set of data gives the dependence of y over x. Approximate
the functional relationship for this data, i.e., y = f(x) as a second order polynomial.
x = [1 2 3 4 5 6 7 8 9 10];
y = [1 4 10 16 25 38 49 64 84 100];

Solution: Execute the following command at your MATLAB prompt after you have
entered the given values of x and y:

Dr. R.N. Patel, email: 221
Curve Fitting
>> polyfit(x,y, 2)
ans =
0.9886 0.2341 -0.2500

The above response indicates the approximation of the
polynomial relation y = f(x) for the given data where the
resultant array of coefficients is for descending powers of x:

Next, you may evaluate the values of y as given by the above
function by the command polyval:

2500 . 0 2341 . 0 9886 . 0
+ = x x y
Dr. R.N. Patel, email: 222
Curve Fitting
>> z = polyval (ans,x)
z =
Columns 1 through 8
0.9727 4.1727 9.3500 16.5045 25.6364 36.7455 49.8318 64.8955
Columns 9 through 10
81.9364 100.9545

Thus, the error between the actual values of y and polynomial approximation is given
by the following array:

>> error = z-y
error =
Columns 1 through 8
-0.0273 0.1727 -0.6500 0.5045 0.6364 -1.2545 0.8318 0.8955
Columns 9 through 10
-2.0636 0.9545

Dr. R.N. Patel, email: 223
Basic Fitting interface at MATLAB figure window
Dr. R.N. Patel, email: 224
Numerical Optimization
MATLAB treats the optimization problem as a minimization problem. In case
you want to find the maximum value of a function, then you must first
convert it as a minimization function by placing a simple minus sign in

Single variable optimization: MATLAB function fminbnd finds the minimum of
a function of one variable within a fixed interval, for example:

x = fminbnd (f_handle, a, b)

returns a value x that is a local minima of the function in the interval a x b.
Here f_handle is the function handle for either an M-file function or an
anonymous function.

Dr. R.N. Patel, email: 225
Example 6.7: Find the minimum value of the function in the range 0 x 2.

Solution: Lets first create an anonymous function for f(x) and assign the handle to f1
by the following command:

>> f1= inline('x.^3-3*x-5')
f1 =
Inline function:
f1(x) = x.^3-3*x-5

The following command can be used subsequently to get the value of x that gives the
minimum value of f1(x) in the given range of 0 to 2:
>> x = fminbnd(f1, 0, 2)
x =
>> y = f(x) % evaluates the value of function at the above value of x.
y =

Dr. R.N. Patel, email: 226
Multiple variable optimization
MATLAB function fminsearch finds the minimum of a scalar function of
several variables, starting at an initial estimate. Use the following
syntax for evaluation:

>> x = fminsearch(f_handle,x0)

where x0 is a array containing the initial estimate and f_handle is the
function handle for either an M-file function or an anonymous

Dr. R.N. Patel, email: 227
The study and design of a control system includes:


System model are developed by applying fundamental laws like KCL,
these laws to a system may lead to Linear, non-linear, Ordinary
Differential, Partial Differential or Difference equations. These
equations describe the behavior of individual components and input
output characteristics of a control system. The two approaches of
system design and analysis are frequency domain approach and time
domain (state variable ) approach.
Dr. R.N. Patel, email: 228
Symbolic Math Toolbox performs calculation
symbolically in Matlab environment. The following
examples introduce some basic operations available
in Basic Symbolic Math toolbox version.
Example 1: Simplifying an expression.

Dr. R.N. Patel, email: 229
In Matlab command window, we will first need to
define alpha as a symbolic expression.
>> alpha = sym('alpha')

alternately, we may also enter:
>> syms alpha

The commands "sym" and "syms" are Matlab's
reserved words. When "syms" is used by itself at
the command prompt, all defined symbolic values
will be listed.

Dr. R.N. Patel, email: 230
Next, we will enter the expression of z.

>> z = sin(alpha)^2 + cos(alpha)^2;
>> simplify(z)

Matlab will yield "1", as expected:
ans =


Dr. R.N. Patel, email: 231
We may also specify the format of the output in symbolic
calculation by adding the option as shown in the example
>> syms rho
>> rho=0.25
>> sym(rho,'r')

Matlab returns:
ans =

'r' stands for rational form.

Dr. R.N. Patel, email: 232
Derivative of function f(x):
Example 2: Derivative.
We wish to take the derivative of function f(x):
f(x)= x
Matlab command entries:
>> syms x
>> f=x^3-cos(x);
>> g=diff(f) % command for derivative
Matlab returns:
g =

Note that the command "diff" was used to obtain the
derivative of function f.

Dr. R.N. Patel, email: 233
Expressions Involving Many Symbolic Objects
When working with symbolic expressions containing more than one variable,
one of them is treated as an independent variable. If MATLAB is not
explicitly told which variable is independent variable, it usually selects the
one closest to x alphabetically. Consider the following example:

>> syms u v z t; % creates the symbolic variables u, v, z and t
>> p = 2*u^2+3*v-9*(z-t)
% here is an expression involving many variables
p =

You can find out which symbolic variables are there in an expression using the
findsym function as shown below:

>> findsym (p)
ans =
t, u, v, z

Dr. R.N. Patel, email: 234
Expressions Involving Many Symbolic Objects
Suppose you would like to differentiate the above expression for p using diff,
it is interesting to note the variable with respect to which the differentiation
takes place.

>> diff (p)

ans =

The answer is based on MATLAB rule that the independent variable closest in
the alphabetical order to the alphabet x is considered an independent
variable. You can ensure this by using the findsym function in the following

>> findsym(p,1) %finds the first independent variable in the expression
ans =

Dr. R.N. Patel, email: 235
Variable Substitution
>> syms u v z t; % creates the symbolic variables u, v, z and t
>> p = 2*u^2+3*v-9*(z-t)
p =
>> syms x
>> m=subs(p, u, x) %replaces the variable u in p with x
Dr. R.N. Patel, email: 236
Variable Substitution
>> h = subs(p, v, 2)
%replaces the variable v in p with a numeric constant 2.
h =

You can also evaluate an expression after assigning a numeric
value to a variable as shown below:
>> v = 2;
>> h2=eval(p) % gives the same expression as h above
h2 =

Dr. R.N. Patel, email: 237
Intended" variable
Since function f has only one independent variable, the diff command
performed the calculation based on x. If there are more than one
independent variable in a function, you should include the "intended"
variable in the following format:
diff(f, x) where x is the "intended" variable. For example,
We wish to obtain the derivative of the following function
f(x, y)=x

Matlab command entries:
>> syms x y
>> f=x^2+(y+5)^3;
>> diff(f,y)
Matlab returns:
ans =
Note that in this case, the command diff(f,y) is equivalent to

Dr. R.N. Patel, email: 238
Example 3: Integral
To integrate function f(x,y) as shown in Example 2, we will use the command "int" as
shown below.
>> int(f,x)
Matlab returns:
ans =
The syntax of the integral command can be viewed by typing >> help int in Matlab
command window.
If we wish to perform the following definite integral:

Matlab command entry:
>> int(f,y,0,10)
Matlab returns:
ans =


Dr. R.N. Patel, email: 239
Matrix Symbolic Calculation
Example 5: Matrix Symbolic Calculation
This example demonstrates how Matlab handles matrix calculation
First we need to define the symbolic variables:
>> syms a b c d e f g h
Matrix A is then defined as:
>> A=[a b; c d]
A =

[ a, b]
[ c, d]
Next, matrix B is defined as:
>> B=[e f;g h]
Matlab's echo:
B =

[ e, f]
[ g, h]

Dr. R.N. Patel, email: 240
Matrix Symbolic Calculation
The addition of these two matrices yields:
>> C=A+B

C =

[ a+e, b+f]
[ c+g, d+h]
and the product of A and B is:
>> D=A*B

D =

[ a*e+b*g, a*f+b*h]
[ c*e+d*g, c*f+d*h]

Dr. R.N. Patel, email: 241
Matrix Symbolic Calculation
If we wish to evaluate a specific matrix numerically, we simply assign the
numeric values to the appropriate variable then use the command eval as
demonstrate below.
>> a=1;b=2;c=3;d=4;e=5;f=6;e=7;f=8;g=9;h=0;
>> eval(A)
ans =
1 2
3 4
>> eval(B)
ans =
7 8
9 0
>> eval(C)
ans =
8 10
12 4

Dr. R.N. Patel, email: 242
Matrix Symbolic Calculation
The inverse of A can be expressed symbolically:
>> D=inv(A)
D =
[ d/(a*d-b*c), -b/(a*d-b*c)]
[ -c/(a*d-b*c), a/(a*d-b*c)]
Numerically, D is expressed by
>> Dn=eval(inv(A))
Dn =
-2.0000 1.0000
1.5000 -0.5000
As a verification, we may evaluate D directly:

Dr. R.N. Patel, email: 243

Laplace Transform

Laplace transform of a function f(t) is defined as


Laplace transform of a function f(t) can be obtained with
Matlab's function laplace.
Syntax: L =laplace(f)
The usage is demonstrated in the following examples.

Dr. R.N. Patel, email: 244
Laplace Transform
Example 1.
Find the Laplace transform of

Matlab performs Laplace transform symbolically. Thus, we need to first
define the variable t as a "symbol". >> syms t
Next, enter the function f(t):
>> f=5*exp(-2*t);
Finally, enter the following command:
>> L=laplace(f)
Matlab yields the following answer:
L =

We may want to carry out the transformation by hand (or using
Laplace transform table) to verify this result.

Dr. R.N. Patel, email: 245
Inverse Laplace
Example 3.
Find the inverse Laplace transform of

In Matlab Command window:
>> ilaplace(1/s-2/(s+4)+1/(s+5))
Matlab result:
ans =


which is the solution of the differential equation

As an exercise, you should carryout the Laplace transform of the above differential
equation with initial condition y(0) = 0 to arrive to the expression of Y(s) as shown

Dr. R.N. Patel, email: 246
The syntax is:
[r, p, k]=residue(n , d);
Where, n=numerator polynomial, d=denominator polynomial,
r=residue vector, p=pole location vector, k=direct term
If, k=[1,3,5] means direct term is (S
+3s+5). If k=[] means no
direct term. The partial fraction expansion of is thus

Following syntax convert partial fraction expansion back to
polynomial ratio
Dr. R.N. Patel, email: 247
Partial Fraction Expansion
Example:1 Obtain partial fraction of function
>> n=[1 1];
>> d=[1 1 1];
>> [r,p,k]=residue(n,d)
r =
0.5000 - 0.2887i
0.5000 + 0.2887i
p =
-0.5000 + 0.8660i
-0.5000 - 0.8660i
k =
The required partial fraction expansion is:


Dr. R.N. Patel, email: 248
Partial Fraction Expansion
Example:2 Obtain partial fraction of function
Matlab Command
>> n=[0 0 1 3];
d=[1 6 12 8];
>> [r,p,k]=residue(n,d)
r =
p =
k =
. The required partial fractions are:

Dr. R.N. Patel, email: 249
Partial Fraction Expansion
Example:3 Obtain partial fraction of function
Matlab Command
>> n=[1 0 9 1];
d=[1 1 2 2];
>> [r,p,k]=residue(n,d)
r =
1.0000 - 1.7678i
1.0000 + 1.7678i
p =
0.0000 + 1.4142i
0.0000 - 1.4142i
k =
The required partial fractions are:

Dr. R.N. Patel, email: 250
Transfer Function Representation
The command tf is used to find the equivalent
transfer function from given n(s), and d(s)
polynomials. Whereas, command tfdata does
the reverse. The syntax is:
variable_name=tf(n,d) %
With v the transfer function are returned as
row vectors and not cell arrays.
Dr. R.N. Patel, email: 251
Transfer Function Representation
Example: Define in Matlab.

MatLab Command
>> n=[5 15 10];
d=[1 7 20 24 0];
Transfer function:
5 s^2 + 15 s + 10
s^4 + 7 s^3 + 20 s^2 + 24 s
>> [n,d]=tfdata(sys,'v')
n =
0 0 5 15 10
d =
1 7 20 24 0

Dr. R.N. Patel, email: 252
Zeros Poles and Pole Zero Map of a Transfer Function
The command tf2zp is used to obtain the zeros z,
poles p, and gain k, of the transfer function. The
syntax is:
[z,p,k]= tf2zp(n,d)
And to obtain transfer function from p, z, k. we use
following syntax:
Pole zero plot can be obtained by using:
Dr. R.N. Patel, email: 253
Zeros Poles and Pole Zero Map of a Transfer Function
Example: Find poles and zeros

MatLab Command
z =
p =
-2.0000 + 2.0000i
-2.0000 - 2.0000i
k =

Dr. R.N. Patel, email: 254
Printsys command
This command prints the transfer function as a
ratio of two polynomials in variable s.
num/den =

5 s^2 + 15 s + 10
s^4 + 7 s^3 + 20 s^2 + 24 s
Dr. R.N. Patel, email: 255
State Space Representation
State space representation of multi input multi output
dynamic system is described by following matrix
differential equation:

Where, x=state vector x=derivative of state vector
u= input vector, y =output vector, A B C D=system
matrices of constant elements.

Dr. R.N. Patel, email: 256
Transfer Function to State Space Conversion

Syntax is:
[A, B, C, D]=tf2ss(n,d)
Example: Obtain State Space Representation.

Dr. R.N. Patel, email: 257
Transfer Function to State Space Conversion

>> n=[0 0 1 2];
d=[1 10 15 150];
A =
-10 -15 -150
1 0 0
0 1 0
B =
C =

0 1 2
D =

Dr. R.N. Patel, email: 258
State Space To transfer Function
Syntax is:
Issuing the command for previous example gives
n =

0 0.0000 1.0000 2.0000

d =

1.0000 10.0000 15.0000 150.0000

Dr. R.N. Patel, email: 259
Step Response of Linear Dynamic System
Step Response of Linear Dynamic System can be obtained
by using either transfer function approach or state space
The syntax is:
step (n, d) % transfer function approach.
step (n,d,t) % t is user-supplied time vector for simulation.
For discrete-time models, t should be of the form Ti:Ts:Tf
where Ts is the sample time.
step (A,B,C,D) % State Space approach.
step (A,B,C,D,t) % t is user defined prior to use of

Dr. R.N. Patel, email: 260
Step Response of Linear Dynamic System
Example: Plot unit step response of :

Matlab commands
n=[ 0 3 6];
d=[1 3 36];

Dr. R.N. Patel, email: 261
36 3
6 3
) (
+ +
s s
s G
Step Response
Dr. R.N. Patel, email: 262
Step response with user defined time
Matlab commands

n=[ 0 3 6];
d=[1 3 36];
t= 0:0.05:2
Dr. R.N. Patel, email: 263
Step response with user defined time
Dr. R.N. Patel, email: 264
Impulse Response of Control System
The syntax is:
impulse(n,d) %for transfer function
impulse(A,B,C,D) % for state space
Example: Obtain unit impulse response of the

Matlab command
n=[0 0 16];
d=[1 1.6 16];

Dr. R.N. Patel, email: 265
Impulse Response
Dr. R.N. Patel, email: 266
Root Locus Plot Commands
To get an idea about stability and transient response of
any system, Root Locus technique is used. This is a
simple method which provides graphical method of
finding the roots of the characteristic equation. For
obtaining Root Locus we use following syntax:
>> rlocus (n, d)
>> rlocus (n, d,k) % k is the gain
For state-space analysis:
>>rlocus (A,B,C,D)
>> rlocus (A,B,C,D,k)

Dr. R.N. Patel, email: 267
Root Locus Plot
Example: Plot root locus for a system with
transfer function:

Matlab command:
n=[1 2];
d=[3 5 7];
Dr. R.N. Patel, email: 268
Root Locus Plot
Dr. R.N. Patel, email: 269
Root Locus Plot with sgrid command
Dr. R.N. Patel, email: 270
Two functions can be convolved by using the syntax:
where, x and h represent discrete time causal sequences x(n) and h(n).
Example: Convolve the functions
+0.5 , h(n)=2s
Matlab Command
x=[2 1 0 0.5]; h=[2 2 1 1];
4 6 4 4 2 0.5 0.5
Which is same as
+0.5)*( 2s
+s+1)= 4s

Dr. R.N. Patel, email: 271
Bode diagram are logarithmic plots. It has two
graphs i.e. magnitude plot and phase plot, both
plotted against frequency.
Syntax for Bode Plot is:
where w specifies the user defined frequency
w=logspace(d1,d2) , generates n points
logarithmically equally spaced between decades
between 10
to 10
Dr. R.N. Patel, email: 272
Example: Obtain Bode Plot for:

Matlab Command
n=[200 600];
d=conv([1 2 0],[1 4 100]); % conv command for
Dr. R.N. Patel, email: 273
Dr. R.N. Patel, email: 274
Nyquist Plots
Nyquist plots helps in determining the stability of a closed
loop system from open loop frequency response without
determining the closed poles. The syntax is:
nyquist (n, d);
nyquist (n, d,w);
Example: Draw a Nyquist Plot using Matlab for:

Matlab Command
n=[0 0 1];
d=[1 1 1];
nyquist (n, d);

Dr. R.N. Patel, email: 275
Nyquist Plots
Dr. R.N. Patel, email: 276

Dr. R.N. Patel, email: 277
Simulink is a graphical extension to MATLAB for
problem solving, modeling and simulation of
systems. In Simulink, the system equations are
represented on the screen as block diagrams.
The component blocks include sources,
integrator blocks, transfer functions, summing
junctions, measurement blocks etc. as per the
requirement of a specific system. Simulink is
integrated with MATLAB and the data can be
easily transferred between the programs.
Dr. R.N. Patel, email: 278
Starting Simulink
Simulink may be started by typing simulink at the
MATLAB command prompt as below:

>> simulink
Alternately, you may click on the simulink icon located
on the MATLAB toolbar (as shown in Figure 1):

Dr. R.N. Patel, email: 279
Opening a New Model File
A new model file with file extension .mdl can be
opened by the icon shown in the Figure above.
Alternatively you can also open a new model file
using File menu i.e., File>new>model in the
Simulink library browser. You may drag and drop
the appropriate Simulink blocks from the Simulink
block libraries in the new opened file.

Dr. R.N. Patel, email: 280
In order to appreciate the capabilities of Simulink, lets take the
following simple electrical circuit example of Figure 2, where a
series R-L branch is connected to a 10 Volts battery. The
switch S is closed at time t= 0 sec. We want to see the
response for current i as a function of time for 0 to 10 sec.

The general equation for the above may be written as:

10 Volts
R=2 ohm, L=2 H
Dr. R.N. Patel, email: 281
in the present case:

The solution of the above equation would require the techniques of
numerical solution of ordinary differential algorithm as discussed earlier.
Simulink provides a simpler alternative to such problems. We can write
the above equation in the s-domain (i.e., Laplace domain) terms as:

(Note: In order to write the s-domain equation, replace the first order
differential term by s, second order differential term by s
and n

order differential term by s
Simplifying the above equation, we have:

The design steps in the Simulink are discussed in the following sections
Dr. R.N. Patel, email: 282
Creating Blocks
The desired response is given by , which will require the following blocks for
A constant block (from Sources library)
A transfer function block (from the Continuous library)
A scope block to view the response (from Sinks library)

Dr. R.N. Patel, email: 283
Setting the Parameters and Making Connections
Dr. R.N. Patel, email: 284
The final model is shown below

Transfer Fcn
Dr. R.N. Patel, email: 285
Setting the Simulink Configuration Parameters
The configuration parameters contain very important choices such as
the solver type (i.e., solution algorithm), Max/Min step sizes,
tolerance values etc. The choice of these parameters may enhance
the accuracy of the solution and may also increase/decrease the
simulation time considerably. MATLAB takes the default values of
these parameters, in case the user does not give his choice. You
may open the Configuration Parameters window by selecting the
Simulation>Configuration Parameters on the model file window.
Alternatively you may also use Ctrl+E from the keyboard. The
block appears as shown
Dr. R.N. Patel, email: 286
Dr. R.N. Patel, email: 287
Running/stopping the Simulation
You may run the model by selecting Simulation>start (or use ctrl+T)
from the model file window. You may also click on to the icon on the
toolbar (as shown in Figure) of the model file window.

The stop time and stop simulation controls shown in Figure give a very
quick access to control the simulation time and simulation run
respectively. Many times the simulation takes a very long time
particularly for complex models, then you may stop the simulation in
between by clicking on to the Stop Simulation button (or by selection of
Simulation>stop from the toolbar).

Dr. R.N. Patel, email: 288
Display of Response
Dr. R.N. Patel, email: 289
Sending Data to the Workspace
Transfer Fcn
To Workspace
Dr. R.N. Patel, email: 290
Run the model and observe the workspace variables by the following
>> whos
Name Size Bytes Class
simout 1x1 1708 struct array
tout 57x1 456 double array
Grand total is 200 elements using 2164 bytes
>> simout
simout =
time: [57x1 double]
signals: [1x1 struct]
blockName: 'seriesrl3/To Workspace'
It can be observed that the workspace variable simout is a structure, in
which time, signals and blockname are the fields. In order to plot the
output signal with respect to time, use the following command:

>> plot(simout.time, simout.signals.values)

Dr. R.N. Patel, email: 291
The obtained plot may be annotated as you desire, which has
been discussed earlier. Figure below gives the annotated plot.

0 2 4 6 8 10
Time (sec.)

Dr. R.N. Patel, email: 292

Example 2: Modeling a system with initial conditions

A system described by the following equation:

and Initial conditions are: Use Simulink to get
the plot of x for the range of t = 0 to 5 sec.
Expressing the above equation in s-domain: The above
equation can be rewritten as:
The corresponding Simulink model representation can be made as given
Dr. R.N. Patel, email: 293

Note that in Figure, if the point c corresponds to the variable x,
then naturally you should have s.x and s
.x at points b and
a respectively. The inputs to the summation block at points d
and e will then represent x
and x respectively, thus
satisfying the equation.
Dr. R.N. Patel, email: 294
Giving Initial Conditions
Note that integrator1 and integrator2 must be given the initial value for
their corresponding output signals i.e. and respectively. The wrong
values for the initial conditions will result in completely different
responses. The initial conditions to the integrator block may be given by
double clicking the block and going to the initial condition option, as
shown in Figure.

Dr. R.N. Patel, email: 295
System Response
Dr. R.N. Patel, email: 296
Dealing with Complex System Equations
An excitation system is described by the following set of differential-algebraic

Make the Simulink model of the above system; V
is the input and E
is the output
of the given system. Find the response E
for a step change in the input V

Writing the s-domain equations for the set of equations 12.6:

The set of equations (12.6) along with the equations (12.7), which represent a
limiter, can be simulated as the model shown in Figure
Dr. R.N. Patel, email: 297

There are certain new blocks in the above model, for which you may explore
the search window of the Simulink library browser. An arbitrary step
input is chosen. Note that the variables K
, T
, T
and T
have been used
in the above model. Simulink accepts the use of such variables, provided
their values are assigned prior to running the model. For example, in the
present case, run the following M-file to assign the parameters required
(alternatively, you may also assign these values at the MATLAB command

Vb Va
Transfer Fcn2
Transfer Fcn1
Dr. R.N. Patel, email: 298
-------------------- para_exc.m --------------------
Ka = 200,
Ta= 0.15
Tb = 10
Tc= 1

Defining parameters through an m-file is particularly useful in
case the parameters of the model are not known a-priori,
and they are computed through some other program. Figure
below shows both the input and output variables (i.e. V
) on a common Scope window:

Dr. R.N. Patel, email: 299

Dr. R.N. Patel, email: 300
You may also get a clearer plot on a figure window, by using the data stored at the ports Out1
and Out2 of model that are available at the Sinks library of Simulink. The default variable
name is yout. Let us see what is in yout at the MATLAB prompt:
>> yout
yout =
0 0
0 0
0 0
0 0
0 0
0 0.2000
0.0000 0.2000
1.3566 0.2000
2.3367 0.2000
3.0641 0.2000
3.6216 0.2000
4.0648 0.2000
4.4310 0.2000
Dr. R.N. Patel, email: 301

Note that the ports Out1 and Out2 store the values of signals
connected to these ports in a common variable named
yout. The first column being the values of signal connected
to port numbered 1 and at the second column are the values
of signal connected at port 2. You may use n number of
such ports to store your signals. You can use >> yout (:, m),
to get the values of signal connected to port m.
Dr. R.N. Patel, email: 302
Creating Subsystems
While modeling highly complex systems, many times the interconnection
between the blocks becomes very complex and difficult to understand. In
such cases, it is worth making subsystems by taking a portion of the
complete model. You may also have subsystems within subsystems. MATLAB
provides unrestricted hierarchy of such subsystem. MATLAB provides
unrestricted hierarchy of such subsystem. Subsystems can be made in one of
the following two ways:

Method 1:
Construct the model of given system.
Select a portion of components by dragging the left mouse key.
After the selection is made in step b go to Edit menu and select Create
Subsystem. You may also press Ctrl + G after step b.

Dr. R.N. Patel, email: 303
Creating Subsystems
Method 2:
Drag the Subsystem block from Ports and Subsystems library.
Construct the components that you desire to be a part of the
subsystem within the Subsystem block. You may also copy
and paste the selected portion of model from your original
Make proper connections of the subsystem ports at the suitable
place in the main model.

Dr. R.N. Patel, email: 304
Dr. R.N. Patel, email: 305
Masking Subsystems
Masking of subsystem is a powerful feature that allows dynamic display and
assignment of various parameters of the component blocks within a
subsystem. Once you have made a subsystem and added it into your
model, select the subsystem by left mouse click and click on Edit>Mask
Subsystem (or press Ctrl + M) to open the masking pane which opens
the Mask Editor. Here you will find four different panes, whose brief
functioning are as under:
Icon pane: enables user to define the icon for the subsystem, label the
ports etc.
Parameters pane: it is used to create a dialog box, where all the
variables used within the subsystem can be assigned values on a single
Initialization pane: enables user to specify initialization commands for
one or more of the subsystem parameters.
Documentation pane: enables user to title the dialog box created in
(b), to give its short description and write help comments or any
description that you may like to provide on the subsystem that you have

Dr. R.N. Patel, email: 306
Dr. R.N. Patel, email: 307
Dr. R.N. Patel, email: 308
Dr. R.N. Patel, email: 309
Dr. R.N. Patel, email: 310
The Dialog Box of masked subsystem
Dr. R.N. Patel, email: 311
Dr. R.N. Patel,