Anda di halaman 1dari 312

1

by
R. N. PATEL,
Ph. D., IIT Delhi
Professor and Coordinator IIPC
Shri Sankaracharya College of Engineering
& Technology, Bhilai
WELCOME !
Dr. R.N. Patel, email: ramnpatel@gmail.com 2
Session-1
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?

Assembly
High Level
Languages such as
C, Pascal etc.
Matlab
Dr. R.N. Patel, email: ramnpatel@gmail.com 3
MATLAB = MATrix LABoratory
Official Website:
www.mathworks.com,
Advantages of MATLAB
Ease of use
Platform independence
Predefined functions
Plotting
Disadvantages of MATLAB
Can be slow
Commercial software
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 6
MATLAB
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: ramnpatel@gmail.com 7
MATLAB Customers
Commercial - US
Allied Signal
Bell Helicopter
Boeing
Harris
Honeywell
Lockheed/Martin
Northrop-Grumman
Pratt and Whitney
Raytheon Sys. Co.
Sikorsky
TRW
International
Aerospatiale
Airbus Consortium
Alenia
British Aerospace
CASA
DERA
IAI
Matra
Sagem
Spar Aerospace
SNECMA
Government
Air Force (US and
others)
Canadian Space
Agency
DoD
European Space
Agency
Ministry of Def
NASA (all facilities)
Navy (US and others)
NSA
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 9
The MathWorks Products
Control
Control System
Robust Control
Mu-Analysis
Nonlinear Control
Quantitative Fback
LMI Control
Model Predictive
Simulation
& Code generation
SIMULINK
Stateflow
Real-Time Workshop
Fixed Point Blockset
RTW Ada Extension

Signal Processing
Signal Processing
DSP Blockset
Wavelets
Communications
Language
MATLAB
MATLAB Compiler



System
Identification
System ID
Frequency-Domain
System ID
General
Optimization
Spline
Statistics
Symbolic Math
NAG
Database

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

Partners
ADI (Beacon)
dSPACE RTI
VxWorks - Wind River
SD/Fast - Symbolic Dynamics
Maple V - Waterloo Maple
Saber - Analogy
ADAMS - MDI
DADS - CADSI
Teamwork - CADRE
Dr. R.N. Patel, email:
ramnpatel@gmail.com
10
Introduction to MATLAB
Desktop
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 13
The MATLAB Desktop
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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;
Example:
>>x=5;
>>x1=2;
Dr. R.N. Patel, email: ramnpatel@gmail.com 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
arr(3,2)
Variables in MATLAB
Dr. R.N. Patel, email: ramnpatel@gmail.com 17
Arrays
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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 19
MATLAB BASICS
Variables
Variable names must begin with a letter, followed by any
combination of letters, numbers and the underscore (_)
character.

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: ramnpatel@gmail.com 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
-308
to 10
308
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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 22
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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
editor.
Dr. R.N. Patel, email: ramnpatel@gmail.com 26
Change the display format Change the values of the
array elements
MATLAB Array Editor
Window
MATLAB Workspace





Dr. R.N. Patel, email: ramnpatel@gmail.com 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
on MATLAB.


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: ramnpatel@gmail.com 28
Dr. R.N. Patel, email: ramnpatel@gmail.com 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
simple.m:

Dr. R.N. Patel, email: ramnpatel@gmail.com 30
-----------------simple.m--------------------------------
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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 32
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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
following:

>> help help
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 36
Special Values
MATLAB includes a number of predefined special values.
These values can be used at any time without initializing
them.
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
calculations.
>> circ1 = 2 * pi * 10;
>> pi = 3;
>> circ2 = 2 * pi * 10;
Never change the values of predefined variables.
Dr. R.N. Patel, email: ramnpatel@gmail.com
37
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
numbers
ans: stores the result of an expression
Dr. R.N. Patel, email: ramnpatel@gmail.com
38
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
following:

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

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: ramnpatel@gmail.com 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 =
5

>> newvar = 20.197
newvar =
20.1970

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

Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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
b
a ^ b
Dr. R.N. Patel, email:
ramnpatel@gmail.com
43
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 =
9
Dr. R.N. Patel, email:
ramnpatel@gmail.com
44
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
3
+ 5/x
5

3. 5 x
1/3
+ 9 y
0.173

4. 3 tan(x)/ (1+ sin
2
(x))
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:
ramnpatel@gmail.com
45
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 =
3.1416
>> format long % change the display format to long
>> pi
ans =
3.14159265358979
Dr. R.N. Patel, email: ramnpatel@gmail.com 46
>> format long e
>> pi
ans =
3.141592653589793e+000
>> format hex
>> pi
ans =
400921fb54442d18


Dr. R.N. Patel, email: ramnpatel@gmail.com 47
>> format compact
>> x = 2, y = 3,
x =
2
y =
3
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: ramnpatel@gmail.com 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:
ramnpatel@gmail.com
49
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: ramnpatel@gmail.com 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
prompt.
Dr. R.N. Patel, email: ramnpatel@gmail.com 51
Summary

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
Continuation
% Comments
Dr. R.N. Patel, email: ramnpatel@gmail.com 52
Exercises
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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 54
Session-2
Vectors, Matrices and Operators in MATLAB
Dr. R.N. Patel, email: ramnpatel@gmail.com
55
The MATLAB Array
Creating Vectors and Matrices
Creating Sub Matrices of a Given Matrix
Changing the Elements of a Given Matrix
Creating Special Matrices
Concatenation
Operators
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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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 =
Sitaram
Dr. R.N. Patel, email: ramnpatel@gmail.com 58
BASIC RULES

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
same.
Dr. R.N. Patel, email: ramnpatel@gmail.com 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 =
2
>> B(1,3)
ans =
7
>> C(1)
ans =
S
Dr. R.N. Patel, email: ramnpatel@gmail.com 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 =
5
>> 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: ramnpatel@gmail.com 61
>> [m n]=size(B) % returns the number of rows and columns in b as
% separate output variables
m =
3
n =
3
>> C= 'Sitaram'
C =
Sitaram
>> length(C)
ans =
7
>> C(length(C)-2) % This is equivalent to writing >> c(7-2)
ans =
r
You can also access the last element in a vector using end variable as shown below:
>> C(end) % Access the last element
ans =
m

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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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
where,
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: ramnpatel@gmail.com 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
vectors:

>> 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: ramnpatel@gmail.com 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
x1
,
the last element is 10
x2
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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 68

>> A(3,1) % (3rd row, 1st Column) entry
ans =
11
>> A(2,3)
ans =
6
>> 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 =
5
6
7
5
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 70
A([2 4], :) returns rows 2 and 4 and all columns. The output is 2 3 matrix as shown
below:
>> A([2 4], :)
ans =
2 4 6
3 4 5

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

>> A(:)
ans =
1
2
11
3
3
4
9
4
5
6
7
5
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 78
Concatenation

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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 81
Operators
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
MATLAB:
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
Negation
* Multiplication
^ Power
' Transpose (real) or
Conjugate transpose
(complex)
.' Transpose (real or
complex)
\ Left division
/ Right division
Dr. R.N. Patel, email:
ramnpatel@gmail.com
82
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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 84
The operators can also be applied to vectors and matrices as
well.
>> 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
way:
>> 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: ramnpatel@gmail.com 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'.

>> A=[1;3;5] % creates a column matrix A
A =
1
3
5
>> 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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
below:
>> 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: ramnpatel@gmail.com 91
Example: Solving the system of equations
2x
1
+ 8x
2
+ 2x
3
= 26
3x
1
+ 4x
2
+ 6x
3
= 12
6x
1
+ 2x
2
+ 4x
3
= 14

Solution:
The given system of equation can be written in matrix form as:
A*X = B
Where, X = [x
1
x
2
x
3
]' , 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 =
26
12
14

Dr. R.N. Patel, email: ramnpatel@gmail.com 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 =
2.0000
3.0000
-1.0000

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

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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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
below:
>> 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: ramnpatel@gmail.com 96
The use of . Element
Operation
K= x^2
Erorr:
??? Error using ==> mpower Matrix must be square.
B=x*y
Erorr:
??? 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 ,:)

y=
3 4 -1
b = x .* y

b=
3 8 -3
c = x . / y

c=
0.33 0.5 -3
d = x .^2

d=
1 4 9
x = A(1,:)

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

>> a=3; b=7;

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

Dr. R.N. Patel, email: ramnpatel@gmail.com 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 =
1
Dr. R.N. Patel, email: ramnpatel@gmail.com 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 =
0

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: ramnpatel@gmail.com 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 =
1
>> 2>3|(1+2i)<2
ans =
1
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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 =
-63
>> rank(A) % is the rank of matrix A
ans =
4
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 107
Thank You !

For your Patience and Attention
Dr. R.N. Patel, email: ramnpatel@gmail.com 108
Session-3
MATLAB Graphics and Plotting
Dr. R.N. Patel, email:
ramnpatel@gmail.com
109
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: ramnpatel@gmail.com 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:
plot(X,Y)
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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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;
plot(X,Y,'r:')
----------------------------------------------------------
Note that the third argument has r standing for red color and : for dotted
lines.

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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 116
Adding Text

A title will be placed in the center and above the plot figure with the
command:
>> 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: ramnpatel@gmail.com 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:
text(x_coordinate,y_coordinate,'textstring')

- Using the gtext command: The syntax of this command is:
gtext('textstring')

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: ramnpatel@gmail.com 118
Following is the complete m-file to summarize what you learnt
so far about the plot aesthetics:
---------------------------add_text.m-----------------------------
% 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 121
For example, the command below labels the figure depicting
plot(X,Z):

>> 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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:
-------------------------mult_plot1.m-----------------------------
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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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
issued.

-------------------------------------- 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: ramnpatel@gmail.com 126
Subplotting

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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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
:
subplot(m,n,p)

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
partition.
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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
subplot(2,2,3)
plot(X,W)
--------------------------------------------------------------------------
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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.)
Essentials
Luxuries
Entertainment
Childrens Education
Medical Care
Savings
5, 000
8, 000
2, 000
5, 000
1, 500
2, 500
Grand Total (Rs.) 24, 000

Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 139
Advanced Concepts on Plot
Annotation and Labeling
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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
below:
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: ramnpatel@gmail.com 142
Next, you can change any of the enlisted properties such as FontName using set
command. The format of set command is as follows:
set(H,'PropertyName',PropertyValue)
You can also set multiple property values with a single statement using the
following format of set command:
set(H,'PropertyName1',PropertyValue1,'PropertyName2',PropertyValue2,.............)
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: ramnpatel@gmail.com 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
t
= Q
0
. e
-. t

where, Q
t
is the amount of radio-active C14 present at present
time, Q
0
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: ramnpatel@gmail.com 144
Solution:
The equation can be written as:
t = - 1/ . log
e
(Q
t
/Q
0
)
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
t
= 0.5Q
0
.

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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 146
The Plot
0 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000
10
20
30
40
50
60
70
80
90
100
Time elapsed in years

%

o
f

C
-
1
4

r
e
m
a
i
n
i
n
g
Q
t
/Q
0
= e
-.t
half life period of C-14
Q
t
/Q
0
= e
-.t
half life period of C-14
Dr. R.N. Patel, email:
ramnpatel@gmail.com
147
LaTeX syntax for Upper and Lower case Greek letters and Mathematical Symbols

Lower case letters
Upper
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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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
interval
(-10 < t < 10 ), taking the time along z-axis.

The m-file for the problem is given below:
Dr. R.N. Patel, email: ramnpatel@gmail.com 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
xlabel('x')
ylabel('y')
zlabel('time')
grid % sets the grid lines to the plot.
%grid off remove them
----------------------------------------------------------------------------------------
Dr. R.N. Patel, email: ramnpatel@gmail.com 152
Now execute the following:
>> sphere(30);
>> figure

>> cylinder([1 0])
>> title('Unit cone')
Dr. R.N. Patel, email: ramnpatel@gmail.com 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.

e.g.
Let us take the simple exponential equation ( y = e
5t
-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: ramnpatel@gmail.com 154
Suppose, there is function in x and y as:
x
2
+ y
2
- 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
prompt:

>> ezplot('x^2 + y^2 - 4*x*y + 1/5',[-3,3])
Dr. R.N. Patel, email: ramnpatel@gmail.com 155
-1
-0.5
0
0.5
1
-1
-0.5
0
0.5
1
0
0.2
0.4
0.6
0.8
1
Thank You !
Dr. R.N. Patel, email: ramnpatel@gmail.com 156
Session-4
Control Structures, Loops, and Functions
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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)
disp('Pass')
end % it wont display anything unless you put an end
% there
Dr. R.N. Patel, email: ramnpatel@gmail.com 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 =
5
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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');
else
disp('Grade: F');
disp('You have to take the course again');
end
------------------------------------------------------------------

Dr. R.N. Patel, email: ramnpatel@gmail.com 162
if (logical expression)
statements
else
statements
end
switch switch_expr
case case_expr1
statements
case case_expr2
statements
case case_expr3
statements
otherwise
statements
end
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:
ramnpatel@gmail.com
163
% 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')
otherwise
disp ('Not a valid entry for the day')
end
Dr. R.N. Patel, email: ramnpatel@gmail.com 164
Loops
The general form and syntax of these loops are as
below:
for variable = init_value: step : final_value
statements
end
while (expression)
statements
end
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:
ramnpatel@gmail.com
165
% factorial using a for loop
n = input ('input the number : ');
fact_n = n;
for i = 1: n-1
fact_n = fact_n*i;
end
disp ( 'factorial of the number is :'),
disp (fact_n);
Dr. R.N. Patel, email: ramnpatel@gmail.com 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;
end
disp ( 'factorial of the number is :'), disp (fact_n);
-------------------------------------------------------------------------------------------

Dr. R.N. Patel, email: ramnpatel@gmail.com 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
end
fact_n = n;
for i = 1: n-1
fact_n = fact_n*i;
end
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);
end
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 170
Example 4.3
The exponential power of x is approximated by the
following infinite series:
e
x
= 1+ x + (x
2
/ 2!) + (x
3
/ 3!) + (x
4
/ 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: ramnpatel@gmail.com 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;
end

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

Dr. R.N. Patel, email: ramnpatel@gmail.com 172


Scripts and Functions

Dr. R.N. Patel, email: ramnpatel@gmail.com 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
program.
Dr. R.N. Patel, email: ramnpatel@gmail.com 174
------------------- sq_root.m -----------------------
function output = sq_root(x)
% Computes the square root of absolute value of x
if (x<0)
x=-x;
end
output = sqrt(x);
----------------------------------------------------------
Observe the following commands:
>> x = -3;
>> y = sq_root(x)
y = 1.7321
>> x
x = -3
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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 = +
1
tan ( )
y
x
u

=
zcyl z =
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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 =
14.1421
% 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 180
Example
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: ramnpatel@gmail.com 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
else
Y(i) = log10(X(i));
end
end
disp('Finished executing func_log_positive...');
-------------------------------------------------------------------

Dr. R.N. Patel, email: ramnpatel@gmail.com 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
arguments.
Dr. R.N. Patel, email: ramnpatel@gmail.com 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));
end
---------------------------------------------------------------
Dr. R.N. Patel, email: ramnpatel@gmail.com 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
commands:

>> [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
below:
>> [x y] = stat([1 2 3])
Computing Std. Deviation
x = 2
y = 0.8165
Dr. R.N. Patel, email: ramnpatel@gmail.com 185
Subfunctions

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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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 =
-5.5745
2.5836
-0.7951
0.7860
>> 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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;
return
else

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

Dr. R.N. Patel, email: ramnpatel@gmail.com 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
are:
A stopping or terminating condition is assigned a
value
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
condition.
Calling the function itself to compute the value of the
function for a reduced input number.

Dr. R.N. Patel, email: ramnpatel@gmail.com 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 =
4

Dr. R.N. Patel, email: ramnpatel@gmail.com 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 =
2.5574

Dr. R.N. Patel, email: ramnpatel@gmail.com 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 =
1.0986

Dr. R.N. Patel, email: ramnpatel@gmail.com 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
function
}
2
1
). (
t
t
dt t f
Dr. R.N. Patel, email: ramnpatel@gmail.com 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 =
1.47854535858791

}
+
+
=
1
0
2
.
1
. 2 1
dx
x
x
I
Dr. R.N. Patel, email: ramnpatel@gmail.com 198
Method-2
>> tol = [1e-3]; % defines new absolute error tolerance

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

I =
1.47854599762368
nfev =
13

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: ramnpatel@gmail.com 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
10
-6
using recursive adaptive Lobatto quadrature.

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

I =
1.47854546052199
nfev =
18


Dr. R.N. Patel, email: ramnpatel@gmail.com 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 =
-0.22176852942704

} }
= =

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

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


Thus, the next value of x will be:

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

abs( x
(i+1)
- x
(i)
)

c,

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

Dr. R.N. Patel, email: ramnpatel@gmail.com 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
end
Dr. R.N. Patel, email: ramnpatel@gmail.com 203
GS solution for a System of Equations
Consider the system of n-equations, with n unknowns, given as:
f
1
(x
1
, x
2
, x
3
,., x
n
) = c
1

f
2
(x
1
, x
2
, x
3
,., x
n
) = c
2

f
3
(x
1
, x
2
, x
3
,., x
n
) = c
3

...............................................
f
n
(x
1
, x
2
, x
3
,., x
n
) = c
n

Solution by GS method will require rearranging the equations in the following form:
x
1
= c
1
+ g
1
(x
1
, x
2
, x
3
,., x
n
)
x
2
= c
2
+ g
2
(x
1
, x
2
, x
3
,., x
n
)
x
3
= c
3
+ g
3
(x
1
, x
2
, x
3
,., x
n
)
.....................................................
x
n
= c
n
+ g
n
(x
1
, x
2
, x
3
,., x
n
)

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


Where, g
1
, g
2
, g
n
are the new functions of x
1
, x
2
,., x
n


Start with a initial set estimate of n variables (x
1
0
, x
2
0
, x
3
0
,., x
n
0
) 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
k
(i+1)
x
k
(i)
)

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

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




x
1
= x
0
+ A t







) , ( t x f
dt
dx
=
.
0
x
dt
dx
2 2.5 3 3.5 4
0
10
20
30
40
50
60
time, t
v
a
r
i
a
b
l
e
,

x
slope at the initial point
of the interval
interval
del(t)
t0
x0
x
i+1
= x
i
+ .
i
x
dt
dx
A t
Dr. R.N. Patel, email: ramnpatel@gmail.com 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
1
= x







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

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

and x
2
=
dt
dx
; the resulting equations will be:

2
1
x
dt
dx
=
and,
1
2
1
2
x x
dt
dx
=
Dr. R.N. Patel, email: ramnpatel@gmail.com 207
% Solution of a Differential Equation using Euler's method
clc
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
end
plot(y(:,1), y(:,2)) % plots time versus x (= x(1))
xlabel ('time, t')
ylabel ('var, x')
box

Dr. R.N. Patel, email: ramnpatel@gmail.com 208
Solution of Differential Equations through ODE
Functions
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: ramnpatel@gmail.com 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
th
order equation:
0 .......
0 1
2
2
2
1
1
1
= + + + + +

a
dt
dx
a
dt
x d
a
dt
x d
a
dt
x d
a
n
n
n
n
n
n
, can be defined by
following n equations:

2
1
x
dt
dx
dt
dx
= = ;
3
2
2
2
x
dt
dx
dt
x d
= = ;
4
3
3
3
x
dt
dx
dt
x d
= = .
n
n
n
n
x
dt
dx
dt
x d
= =

1
1
1
;
and ) . .......... (
1
1 3 2 2 1 0 n n
n
n
n
n
x a x a x a a
a dt
dx
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
1
, x
2
, , x
n
as its output.
3. Obtain the initial conditions of the variables x
1
, x
2
, , x
n
and take them in the
corresponding sequence as an array of initial conditions, i.e. x0 = [ x
1
(0), x
2
(0),
, x
n
(0)]
4. Get the time span for solution of the equations; i.e. tspan = [t
initial
, t
final
] in
seconds.
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
1
, x
2
, , x
n
as a matrix with n columns
at specified points of time given by vector t.
Dr. R.N. Patel, email: ramnpatel@gmail.com 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.
0
2
2
2
= + x x
dt
x d
, where x = f(t) and Initial conditions are:
x(0) = 0.5 and 0
0
=
dt
dx

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


2
1
x
dt
dx
= and,
1
2
1
2
x x
dt
dx
=

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

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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 212
Example-2
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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 214
Session-5
SOME APPLICATIONS OF MATLAB

Dr. R.N. Patel, email: ramnpatel@gmail.com 215
Interpolation
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:

y
i
= interp1(x,y, x
i
, method)

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

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

Dr. R.N. Patel, email: ramnpatel@gmail.com 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.

Solution:

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 =
233.5000

Dr. R.N. Patel, email: ramnpatel@gmail.com 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 =
271.9286

Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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
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
figure;
mesh(xi, yi, zi), % plot of interpolated values
title('cubic spline interpolation of z')

Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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
2
+ = x x y
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 223
Basic Fitting interface at MATLAB figure window
Dr. R.N. Patel, email: ramnpatel@gmail.com 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
front.

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: ramnpatel@gmail.com 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 =
1.0000
>> y = f(x) % evaluates the value of function at the above value of x.
y =
-7.0000

Dr. R.N. Patel, email: ramnpatel@gmail.com 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
function.


Dr. R.N. Patel, email: ramnpatel@gmail.com 227
MATLAB APPLICATIONS
The study and design of a control system includes:

Modeling
Simulation
Analysis
Optimization

System model are developed by applying fundamental laws like KCL,
KVL, NEWTONS LAW, THERMODYNAMICS LAWS etc. application of
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: ramnpatel@gmail.com 228
SYMBOLIC CALCULATION
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.
Simplify

Dr. R.N. Patel, email: ramnpatel@gmail.com 229
SYMBOLIC CALCULATION
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: ramnpatel@gmail.com 230
SYMBOLIC CALCULATION
Next, we will enter the expression of z.

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

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

1

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

Matlab returns:
ans =

1/4
'r' stands for rational form.

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

3*x^2+sin(x)
Note that the command "diff" was used to obtain the
derivative of function f.

Dr. R.N. Patel, email: ramnpatel@gmail.com 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 =
2*u^2+3*v-9*z+9*t

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: ramnpatel@gmail.com 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 =
-9

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
format:

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

Dr. R.N. Patel, email: ramnpatel@gmail.com 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 =
2*u^2+3*v-9*z+9*t
>> syms x
>> m=subs(p, u, x) %replaces the variable u in p with x
m=
2*x^2+3*v-9*z+9*t
Dr. R.N. Patel, email: ramnpatel@gmail.com 236
Variable Substitution
>> h = subs(p, v, 2)
%replaces the variable v in p with a numeric constant 2.
h =
2*u^2+6-9*z+9*t

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 =
2*u^2+6-9*z+9*t

Dr. R.N. Patel, email: ramnpatel@gmail.com 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
2
+(y+5)
3

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





Dr. R.N. Patel, email: ramnpatel@gmail.com 238
Integral
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 =
1/3*x^3+(y+5)^3*x
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 =

12500+10*x^2



Dr. R.N. Patel, email: ramnpatel@gmail.com 239
Matrix Symbolic Calculation
Example 5: Matrix Symbolic Calculation
This example demonstrates how Matlab handles matrix calculation
symbolically.
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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 243

Laplace Transform

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


Where,

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: ramnpatel@gmail.com 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 =

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


Dr. R.N. Patel, email: ramnpatel@gmail.com 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 =

1-2*exp(-4*t)+exp(-5*t)
or

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

Dr. R.N. Patel, email: ramnpatel@gmail.com 246
PARTIAL FRACTION EXPANSION USING MATLAB
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
2
+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
[n,d]=residue(r,p,k)
Dr. R.N. Patel, email: ramnpatel@gmail.com 247
Partial Fraction Expansion
Example:1 Obtain partial fraction of function
F(s)=(s+1)/(s
2
+s+1)
MATLAB COMMAND
>> n=[1 1];
>> d=[1 1 1];
>> [r,p,k]=residue(n,d)
Output
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: ramnpatel@gmail.com 248
Partial Fraction Expansion
Example:2 Obtain partial fraction of function
F(s)=(s+3)/(s
3
+6s
2
+12s+8)
Matlab Command
>> n=[0 0 1 3];
d=[1 6 12 8];
>> [r,p,k]=residue(n,d)
Result
r =
0
1.0000
1.0000
p =
-2.0000
-2.0000
-2.0000
k =
[]
. The required partial fractions are:



Dr. R.N. Patel, email: ramnpatel@gmail.com 249
Partial Fraction Expansion
Example:3 Obtain partial fraction of function
F(s)=(s
3
+9s+1)/(s
3
+s
2
+2s+2)
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
-3.0000
p =
0.0000 + 1.4142i
0.0000 - 1.4142i
-1.0000
k =
1
The required partial fractions are:
.





Dr. R.N. Patel, email: ramnpatel@gmail.com 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) %
[n,d]=tfdata(variable_name,v)
With v the transfer function are returned as
row vectors and not cell arrays.
Dr. R.N. Patel, email: ramnpatel@gmail.com 251
Transfer Function Representation
Example: Define in Matlab.

MatLab Command
>> n=[5 15 10];
d=[1 7 20 24 0];
sys=tf(n,d)
Result
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: ramnpatel@gmail.com 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:
[n,d]=zp2tf(z,p,k).
Pole zero plot can be obtained by using:
pzmap(n,d)
Dr. R.N. Patel, email: ramnpatel@gmail.com 253
Zeros Poles and Pole Zero Map of a Transfer Function
Example: Find poles and zeros

MatLab Command
[z,p,k]=tf2zp(n,d)
Result
z =
-2
-1
p =
0
-3.0000
-2.0000 + 2.0000i
-2.0000 - 2.0000i
k =
5

Dr. R.N. Patel, email: ramnpatel@gmail.com 254
Printsys command
printsys(n,d,'s')
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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 257
Transfer Function to State Space Conversion

>> n=[0 0 1 2];
d=[1 10 15 150];
[A,B,C,D]=tf2ss(n,d)
A =
-10 -15 -150
1 0 0
0 1 0
B =
1
0
0
C =

0 1 2
D =

0
Dr. R.N. Patel, email: ramnpatel@gmail.com 258
State Space To transfer Function
Syntax is:
[n,d]=ss2tf(A,B,C,D)
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: ramnpatel@gmail.com 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
approach.
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
command.

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



Matlab commands
n=[ 0 3 6];
d=[1 3 36];
step(n,d)



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

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

Matlab command
n=[0 0 16];
d=[1 1.6 16];
impulse(n,d)

Dr. R.N. Patel, email: ramnpatel@gmail.com 265
Impulse Response
Dr. R.N. Patel, email: ramnpatel@gmail.com 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)
or
>> 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: ramnpatel@gmail.com 267
Root Locus Plot
Example: Plot root locus for a system with
transfer function:

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

Dr. R.N. Patel, email: ramnpatel@gmail.com 271
BODE PLOTS
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:
bode(n,d)
bode(n,d,w)
where w specifies the user defined frequency
range.
w=logspace(d1,d2) , generates n points
logarithmically equally spaced between decades
between 10
d1
to 10
d2
Dr. R.N. Patel, email: ramnpatel@gmail.com 272
BODE PLOTS
Example: Obtain Bode Plot for:


Matlab Command
n=[200 600];
d=conv([1 2 0],[1 4 100]); % conv command for
convolution
bode(n,d);
Dr. R.N. Patel, email: ramnpatel@gmail.com 273
BODE PLOTS
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 275
Nyquist Plots
Dr. R.N. Patel, email: ramnpatel@gmail.com 276
Session-6


Dr. R.N. Patel, email: ramnpatel@gmail.com 277
Introduction
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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 280
Example
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:


i
S
10 Volts
R=2 ohm, L=2 H
Dr. R.N. Patel, email: ramnpatel@gmail.com 281
Example
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
2
and n
th

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


The design steps in the Simulink are discussed in the following sections
Dr. R.N. Patel, email: ramnpatel@gmail.com 282
Creating Blocks
The desired response is given by , which will require the following blocks for
simulation:
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: ramnpatel@gmail.com 283
Setting the Parameters and Making Connections
Dr. R.N. Patel, email: ramnpatel@gmail.com 284
The final model is shown below


1
2s+2
Transfer Fcn
Scope
10
Constant
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 286
.
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 288
Display of Response
Dr. R.N. Patel, email: ramnpatel@gmail.com 289
Sending Data to the Workspace
1
2s+2
Transfer Fcn
simout
To Workspace
Scope
10
Constant
Dr. R.N. Patel, email: ramnpatel@gmail.com 290
Run the model and observe the workspace variables by the following
command:
>> 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: ramnpatel@gmail.com 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
0
1
2
3
4
5
Time (sec.)
C
u
r
r
e
n
t

(
A
m
p
.
)
Dr. R.N. Patel, email: ramnpatel@gmail.com 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.
Solution:
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: ramnpatel@gmail.com 293









Note that in Figure, if the point c corresponds to the variable x,
then naturally you should have s.x and s
2
.x at points b and
a respectively. The inputs to the summation block at points d
and e will then represent x
2
and x respectively, thus
satisfying the equation.
c
b
a
d
e
Scope
Product
1/s
Integrator2
1/s
Integrator1
Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 295
System Response
Dr. R.N. Patel, email: ramnpatel@gmail.com 296
Dealing with Complex System Equations
.
An excitation system is described by the following set of differential-algebraic
equations:






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

Solution:
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: ramnpatel@gmail.com 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
A
, T
A
, T
B
and T
C
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
prompt).


Vi
V1
Vb Va
Efd
Vi
2
Out2
1
Out1
Ka
Ta.s+1
Transfer Fcn2
1-Tc/Tb
Tb.s+1
Transfer Fcn1
Step
Scope
Saturation
Tc/Tb
Gain
Dr. R.N. Patel, email: ramnpatel@gmail.com 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
I
and
E
FD
) on a common Scope window:

Dr. R.N. Patel, email: ramnpatel@gmail.com 299



Dr. R.N. Patel, email: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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: ramnpatel@gmail.com 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
model.
Make proper connections of the subsystem ports at the suitable
place in the main model.

Dr. R.N. Patel, email: ramnpatel@gmail.com 304
Example
Dr. R.N. Patel, email: ramnpatel@gmail.com 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
window.
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
created.

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

Anda mungkin juga menyukai