Control & Simulation Lab-I Manual: Vector and Matrix

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 93

Control & Simulation Lab-I Manual

CHAPTER 1
Vector and Matrix
1. Vectors: A vector is a one-dimensional array of numbers. MATLAB allows creating
two types of vectors:
 Row vectors
 Column vectors
(a) Row vectors: Row vectors are created by enclosing the set of elements in square
brackets, using space or comma to delimit the elements.
Example:

r = [7 8 9 1 0 1 1]

r =

7 8 9 1 0 1 1

(b) Column Vectors: Column vectors are created by enclosing the set of elements in
square brackets, using a semicolon to delimit the elements.
Example:

c = [7;8;9;10;11]

c =

7
8
9
10
11

(c) Referencing the Elements of a vector : You can reference one or more of the elements
of a vector in several ways. The component of a vector v is referred as .
Example:

v = [1;2;3;4;5;6]
v(3)

v =

1
2
3
4
5
6

ans =

When you reference a vector with a colon, such as v (:), all the components of the vector are
listed.
Example:

v = [1;2;3;4;5;6]
v (:)

v =

1
2
3
4
5
6

ans =

1
2
3
4
5
6

MATLAB allows you to select a range of elements from a vector.


Example, let us create a row vector of 9 elements, then we will reference the elements 3 to
7 by writing and create a new vector named . Example:

rv = [1 2 3 4 5 6 7 8 9]
sub_rv = rv(3:7)

rv =

1 2 3 4 5 6 7 8 9
sub_rv =

3 4 5 6 7

(d) Referencing index of an elements of a vector:

help find

Learn how to use “find” command Example:

c = [7;8;9;10;11]

c =

7
8
9
10
11

Now try the following

find (c==10)

ans =

Also try:

find (c (c == 10))
r = [7 8 9 1 0 1 1]
c (r == 8)

ans =

r =

7 8 9 1 0 1 1

ans =

8
(d) Ascertaining an element in an array

help any

Learn how to use “any” command. Try the following Example:

c = [7;8;9;10;11]

c =

7
8
9
10
11

Now try the following

any (c == 10)

ans =

logical

2. Vector Operations: In this section, let us discuss the following vector operations:
 Addition and Subtraction of Vectors.
 Scalar Multiplication of Vectors.
 Transpose of a Vector.
 Appending Vectors.
 Magnitude of a Vector.
 Vector Dot Product.
 Vectors with Uniformly Spaced Elements.

(i) Addition and Subtraction of Vectors:


 You can add or subtract two vectors. Both the operand vectors must be of same type
and have same number of elements. Example:

A = [7, 11, 15, 23, 9]


B = [2, 5, 13, 16, 20]
C = A + B
D = A - B
A =

7 11 15 23 9

B =

2 5 13 16 20

C =

9 16 28 39 29

D =

5 6 2 7 -11

(ii) Scalar Multiplication of vectors:


 When you multiply a vector by a number, this is called the scalar multiplication.
Scalar multiplication produces a new vector of same type with each element of the
original vector multiplied by the number. Example:

v = [ 12 34 10 8]
m = 5 * v

v =

12 34 10 8

m =

60 170 50 40

Please note that you can perform all scalar operations on vectors. Example, you can add,
subtracts and divides a vector with a scalar quantity.

(iii) Transpose of a Vector:


 The transpose operation changes a column vector into a row vector and vice versa.
The transpose operation is represented by a single quote ('). Example:

r = [ 1 2 3 4]
tr = r'
r =

1 2 3 4

tr =

1
2
3
4

(iv) Appending Vector:


 MATLAB allows you to append vectors together to create new vectors.
 If you have two row vectors r1 and r2 with n and m number of elements, to create a
row vector r of n plus m elements, by appending these vectors, you write: r = [r1, r2].
 You can also create a matrix r by appending these two vectors, the vector r2, will be
the second row of the matrix: r = [r1; r2].
 However, to do this, both the vectors should have same number of elements.
 Similarly, you can append two column vectors c1 and c2 with n and m number of
elements. To create a column vector c of n plus m elements, by appending these
vectors, you write: c = [c1; c2].
 You can also create a matrix c by appending these two vectors; the vector c2 will be
the second column of the matrix: c = [c1, c2].
 However, to do this, both the vectors should have same number of elements.
Example:

r1 = [1 2 3 4]
r2 = [5 6 7 8]
r = [r1, r2]
rMat = [r1; r2]
c1 = [ 1; 2; 3; 4]
c2 = [5; 6; 7; 8]
c = [c1; c2]
cMat = [c1, c2]

r1 =

1 2 3 4

r2 =

5 6 7 8

r =
1 2 3 4 5 6 7 8

rMat =

1 2 3 4
5 6 7 8

c1 =

1
2
3
4

c2 =

5
6
7
8

c =

1
2
3
4
5
6
7
8

cMat =

1 5
2 6
3 7
4 8

(v) Magnitude of a Vector:


 Magnitude of a vector v with elements v1, v2, v3, …, vn, is given by the equation
. You need to take the following steps to calculate
the magnitude of a vector:
 Take the product of the vector with itself, using array multiplication (.*) . This
produces a vector sv, whose elements are squares of the elements of vector v.
.
 Use the sum function to get the sum of squares of elements of vector v. This is also
called the dot product of vector v.
 Use the sqrt function to get the square root of the sum which is also the magnitude of
the vector.
Example:

v = [1 2 20];
sv = v.* v;
dp= sum(sv);
mag = sqrt(dp)

mag =

20.1246

(vi) Vector Dot Product:


Dot product of two vectors and is given by

 Dot product of two vectors a and b is calculated using the dot function. .
Example:

v1 = [2 3 4];
v2 = [1 2 3];
dp = dot (v1, v2)

dp =

20

(vii) Vectors with Uniformly Spaced Elements:


 MATLAB allows you to create a vector with uniformly spaced elements to create a
vector with the first element last element and the difference between elements is
any real number we write:

v = [1: 2: 20]

v =

1 3 5 7 9 11 13 15 17 19

3. Matrix :-
 A matrix is a two-dimensional array of numbers.
 In MATLAB, you create a matrix by entering elements in each row as comma or
space delimited numbers and using semicolons to mark the end of each row.
Example:
Let us create a 4-by-5 matrix a:

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

a =

1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8

(a) Referencing the Elements of a Matrix :


 To reference an element in the row and column, of a matrix , we write:
.
Example:
To refer to the element in the row and column, of the matrix , as created in the last
section, we type:

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


a (2, 5)

ans =
6

To reference all the elements in the mth column we type A (:, m).
Example:
Let us create a column vector v, from the elements of the row of the matrix :

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


v = a (:, 4)

v =

4
5
6
7

You can also select the elements in the through columns, for this we write:
.
Example:
Let us create a smaller matrix taking the elements from the second and third columns:

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


a (:, 2:3)

ans =

2 3
3 4
4 5
5 6

In the same way, you can create a sub-matrix taking a sub-part of a matrix.
Example: let us create a sub-matrix ‘sa’ taking the inner subpart of

To do this, write:
a = [1 2 3 4 5;2 3 4 5 6;3 4 5 6 7;4 5 6 7 8];
sa = a (2:3,2:4)

sa =

3 4 5
4 5 6

(b) Deleting a Row or a Column in a Matrix:


 You can delete an entire row or column of a matrix by assigning an empty set of
square braces [ ] to that row or column. Basically, [ ] denotes an empty array.
Example: let us delete the fourth row of :

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


a (4, :) = [ ]

a =

1 2 3 4 5
2 3 4 5 6
3 4 5 6 7

Next, let us delete the fifth column of :

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


a (:, 5) = [ ]

a =

1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7

4. Matrix Operations:
In this section, let us discuss the following basic and commonly used matrix operations:
 Addition and Subtraction of Matrices
 Division of Matrices
 Scalar Operations of Matrices
 Transpose of a Matrix
 Concatenating Matrices
 Matrix Multiplication
 Determinant of a Matrix
 Inverse of a Matrix
 Trace of a Matrix
 Rank of a Matrix
 Eigen value and Eigen vector of a Matrix

(a) Addition and Subtraction of Matrices:


 You can add or subtract matrices. Both the operand matrices must have the same
number of rows and columns.
Example:

a = [ 1 2 3 ; 4 5 6; 7 8 9];
b = [ 7 5 6 ; 2 0 8; 5 7 1];
c = a + b
d = a - b

c =

8 7 9
6 5 14
12 15 10

d =

-6 -3 -3
2 5 -2
2 1 8

(b) Division of Matrices:


 You can divide two matrices using right (/) division operators. The operand matrices
must have the same number of rows and columns.
 Also see function.
Example:

a = [ 1 2 3 ; 4 5 6; 7 8 9];
b = [ 7 5 6 ; 2 0 8; 5 7 1];
c = a / b
c =

-0.5254 0.6864 0.6610


-0.4237 0.9407 1.0169
-0.3220 1.1949 1.3729

(c) Scalar Operations of Matrices:


 When you add, subtract, multiply or divide a matrix by a number, this is called the
scalar operation.
 Scalar operations produce a new matrix with same number of rows and columns with
each element of the original matrix added to, subtracted from, multiplied by or
divided by the number.
Example:

a = [ 10 12 23 ; 14 8 6; 27 8 9];
b = 2;
c = a + b
d = a - b
e = a * b
f = a / b

c =

12 14 25
16 10 8
29 10 11

d =

8 10 21
12 6 4
25 6 7

e =

20 24 46
28 16 12
54 16 18

f =

5.0000 6.0000 11.5000


7.0000 4.0000 3.0000
13.5000 4.0000 4.5000

(d) Transpose of a Matrix:


 The transpose operation switches the rows and columns in a matrix. It is represented
by a single quote (').
Example:

a = [ 10 12 23 ; 14 8 6; 27 8 9];
b = a'

b =

10 14 27
12 8 8
23 6 9

(e) Concatenating Matrices:


 You can concatenate two matrices to create a larger matrix. The pair of square
brackets '[ ]' is the concatenation operator.
 MATLAB allows two types of concatenations:
(1) Horizontal concatenation
(2) Vertical concatenation
 When you concatenate two matrices by separating those using commas, they are just
appended horizontally. It is called horizontal concatenation.
 Alternatively, if you concatenate two matrices by separating those using semicolons,
they are appended vertically. It is called vertical concatenation.
Example:

a = [ 10 12 23; 14 8 6; 27 8 9];
b = [ 12 31 45; 8 0 -9; 45 2 11];
c = [a, b]
d = [a; b]

c =

10 12 23 12 31 45
14 8 6 8 0 -9
27 8 9 45 2 11

d =

10 12 23
14 8 6
27 8 9
12 31 45
8 0 -9
45 2 11

(f) Matrix Multiplication:


 Consider two matrices A and B. If A is an m x n matrix and B is a n x p matrix, they
could be multiplied together to produce an m x n matrix C.
 Matrix multiplication is possible only if the number of columns n in A is equal to the
number of rows n in B.
 In matrix multiplication, the elements of the rows in the first matrix are multiplied
with corresponding columns in the second matrix.
 Each element in the position, in the resulting matrix C, is the summation of the
products of elements in row of first matrix with the corresponding element in the
column of the second matrix.
 In MATLAB, matrix multiplication is performed by using the * operator.
Example:

a = [ 1 2 3; 2 3 4; 1 2 5];
b = [ 2 1 3; 5 0 -2; 2 3 -1];
prod = a * b

prod =

18 10 -4
27 14 -4
22 16 -6

(g) Determinant of a Matrix:


 Determinant of a matrix is calculated using the det function of MATLAB.
Determinant of a matrix A is given by det(A).
Example:

a = [ 1 2 3; 2 3 4; 1 2 5];
b = det (a)

b =

-2

(h) Inverse of a Matrix:


 The inverse of a matrix A is denoted by A-1 such that the following relationship holds
AA-1=A-1A=1.
 The inverse of a matrix does not always exist. If the determinant of the matrix is zero,
then the inverse does not exist and the matrix is singular.
 In MATLAB, inverse of a matrix is calculated using the inv function. Inverse of a
matrix A is given by inv (A).
 See also “/” or “\”.
Example:

a = [ 1 2 3; 2 3 4; 1 2 5];
b = inv (a)

b =

-3.5000 2.0000 0.5000


3.0000 -1.0000 -1.0000
-0.5000 0 0.5000

(i) Diagonal of a Matrix:


 diag(X) returns the main diagonal of a square matrix X.
Example:

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


diag(X)

ans =

1
5
9

(j) Trace of a Matrix:


 Trace of a matrix is calculated using the trace function of MATLAB. Trace of a matrix
A is given by trace (A).
 trace (A) is the sum of the diagonal elements of the matrix A.

Example:

A = [1 5 8; 4 5 6; 7 8 9];
trace(A)
ans =

15

(k) Rank of a Matrix:


 The rank function provides an estimate of the number of linearly independent rows or
columns of a full matrix.
 Rank of a matrix is calculated using the rank function of MATLAB. Rank of a matrix
A is given by rank(A).
Example:

A = [6 7 9; 3 4 6; 7 2 3];
rank (A)

ans =

(l) Eigen Value and Eigen Vector of a Matrix:


 Eigen value and eigen vector of a matrix is calculated using the eig function of
MATLAB. Eigen value and eigen vector of a matrix A is given by [v,e]=eig(A).
Example:

A = [6 7 9; 3 4 6; 7 2 3];
[v, e] = eig (A)

v =

0.7577 + 0.0000i 0.2651 - 0.0607i 0.2651 + 0.0607i


0.4386 + 0.0000i 0.6407 + 0.0783i 0.6407 - 0.0783i
0.4832 + 0.0000i -0.7137 + 0.0000i -0.7137 + 0.0000i

e =

15.7919 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i


0.0000 + 0.0000i -1.3960 + 0.3755i 0.0000 + 0.0000i
0.0000 + 0.0000i 0.0000 + 0.0000i -1.3960 - 0.3755i

(m) Element wise operations:


Try the following:
c = [1 2 3 4];
d = [5 6 7 8];
e = c .* d
f = e ./ c

e =

5 12 21 32

f =

5 6 7 8

Assignments:

Write a MATLAB Script for each of the queries

1. Create the following matrices.

1 2 3�
� 5 6 7�


A=� � �
6 7 8�
4 5 6� B = � �

6 7 8�
� � � �
7 8 9�

Then evaluate the following expressions.

(i) ( A �B ) + ( A-1 �B )

(ii) A + ( B �A )
T

Use extensive comments in the script to express your intended operations.

2. Create the following Matrix.

5
� 6 7 1�

6 7 8 1�
A=� �

7 8 9 0�
� �
4
� 5 6 4�

Then do the following operations on it.

(a) Create a Matrix B, with only the first three columns as the content of A.
(b) Create a Matrix C, with only the last three rows as the content of A.
(c) Find out the product of B and C, and save it in a Matrix D.
(d) Find out the rank of A, B, C and D
(e) Find out the Eigen Value and Eigen Vector of D
3. Find
(i) Column wise maximum values for the matrix A given in Q.2.
(ii) Row wise maximum values for the matrix A given in Q.2.
4. Find the positions in the matrix contain
(i) value=8 in the matrix A given in Q.2
(ii) value>=6 in the matrix A given in Q.2
5. Find eigenvectors of matrix A given in Q.2. Multiply eigenvectors (v) with the
matrix (A) and find w=A*v. For each v calculate the ratio of the magnitude of
vectors w and v.
6. Explain the result below?

find (c (c == 10))
r = [7 8 9 1 0 1 1]
c (r == 8)

CHAPTER 2
1. Roots:
roots(c) returns a column vector whose elements are the roots of the polynomial c. Row
vector c contains the coefficients of a polynomial, ordered in descending powers.
Example:
The polynomial is represented in MATLAB software
p = [1 -6 -72 -27];
r = roots(p)

r =

12.1229
-5.7345
-0.3884

2. Round:
 round(X) rounds the elements of X to the nearest integers.
 Positive elements with a fractional part of 0.5 rounds up to the nearest positive
integer.
 Negative elements with a fractional part of -0.5 rounds down to the nearest negative
integer.
 For complex X, the imaginary and real parts are rounded independently.

Examples:

a = [-1.9, -0.2, 3.4, 5.6, 7.0, 2.4+3.6i]


round(a)

a =

Columns 1 through 4

-1.9000 + 0.0000i -0.2000 + 0.0000i 3.4000 + 0.0000i 5.6000 + 0.0000i

Columns 5 through 6

7.0000 + 0.0000i 2.4000 + 3.6000i

ans =

Columns 1 through 4

-2.0000 + 0.0000i 0.0000 + 0.0000i 3.0000 + 0.0000i 6.0000 + 0.0000i

Columns 5 through 6

7.0000 + 0.0000i 2.0000 + 4.0000i


3. Floor:
floor (A) rounds the elements of A to the nearest integers less than or equal to A. For
complex A, the imaginary and real parts are rounded independently.
Example:

a = [-1.9 -0.2 3.4 5.6 7.0 2.4+3.6i];


floor(a)

ans =

Columns 1 through 4

-2.0000 + 0.0000i -1.0000 + 0.0000i 3.0000 + 0.0000i 5.0000 + 0.0000i

Columns 5 through 6

7.0000 + 0.0000i 2.0000 + 3.0000i

4. Ceil:
ceil (A) rounds the elements of A to the nearest integers greater than or equal to A. For
complex A, the imaginary and real parts are rounded independently.
Example:

a = [-1.9, -0.2, 3.4, 5.6, 7, 2.4+3.6i];


ceil(a)

ans =

Columns 1 through 4

-1.0000 + 0.0000i 0.0000 + 0.0000i 4.0000 + 0.0000i 6.0000 + 0.0000i

Columns 5 through 6

7.0000 + 0.0000i 3.0000 + 4.0000i

5. Max:
 max (A) returns the largest elements along different dimensions of an array.
 If A is a vector, max (A) returns the largest element in A.
 If A is a matrix, max (A) treats the columns of A as vectors, returning a row vector
containing the maximum element from each column.
 If A is a multidimensional array, max (A) treats the values along the first non-
singleton dimension as vectors, returning the maximum value of each vector.
 C = max (A, B) returns an array the same size as A and B with the largest elements
taken from A or B.
Examples:
(a) Return the maximum of a 2-by-3 matrix from each column:

X = [2 8 4; 7 3 9];
max (X, [ ], 1)

ans =

7 8 9

(b) Return the maximum from each row:

max (X, [ ], 2)

ans =

8
9

(c) Compare each element of X to a scalar:

max (X, 5)

ans =

5 8 5
7 5 9

6. Min:
 C = min(A) returns the smallest elements along different dimensions of an array.
 If A is a vector, min(A) returns the smallest element in A.
 If A is a matrix, min(A) treats the columns of A as vectors, returning a row vector
containing the minimum element from each column.

Examples
(a) Return the minimum of a 2-by-3 matrix from each column:

X = [2 8 4; 7 3 9];
min (X, [ ], 1)

ans =
2 3 4

(b) Return the minimum from each row:

min (X, [ ], 2)

ans =

2
3

(c) Compare each element of X to a scalar:

min(X,5)

ans =

2 5 4
5 3 5

7. Arrays :
 In MATLAB all variables of all data types are multidimensional arrays. A vector is a
one-dimensional array and a matrix is a two-dimensional array.
 We have already discussed vectors and matrices. In this chapter, we will discuss
multidimensional arrays. However, before that, let us discuss some special types of
arrays.

Special Arrays in MATLAB


 In this section, we will discuss some functions that create some special arrays. For all
these functions, a single argument creates a square array, double arguments create
rectangular array.

Examples:

zeros (5)
ones (4, 3)
eye (4)

ans =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

ans =

1 1 1
1 1 1
1 1 1
1 1 1

ans =

1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

The rand( ) function creates an array of uniformly distributed random numbers on (0,1):
Example :

rand (3, 5)

ans =

0.0344 0.7655 0.4898 0.7094 0.6797


0.4387 0.7952 0.4456 0.7547 0.6551
0.3816 0.1869 0.6463 0.2760 0.1626

8. A Magic Square:
 A magic square is a square that produces the same sum, when its elements are added
row-wise, column-wise or diagonally.
 The magic ( ) function creates a magic square array. It takes a singular argument that
gives the size of the square. The argument must be a scalar greater than or equal to 3.

Example:

magic (4)
ans =

16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1

9. Multidimensional Arrays:
 An array having more than two dimensions is called a multidimensional array in
MATLAB. Multidimensional arrays in MATLAB are an extension of the normal two-
dimensional matrix.
 Generally, to generate a multidimensional array, we first create a two-dimensional
array and extend it.

Example:
let's create a two-dimensional array a.

a=[7 9 5; 6 1 9; 4 3 2]

a =

7 9 5
6 1 9
4 3 2

 The array a is a 3-by-3 array; we can add a third dimension to a, by providing the
values like:

a (:, :, 2) = [1 2 3; 4 5 6; 7 8 9]

a(:,:,1) =

7 9 5
6 1 9
4 3 2

a(:,:,2) =

1 2 3
4 5 6
7 8 9

 We can also create multidimensional arrays using the ones ( ), zeros( ) or the rand( )
functions.
b = rand (4, 3, 2)

b(:,:,1) =

0.1190 0.5853 0.5060


0.4984 0.2238 0.6991
0.9597 0.7513 0.8909
0.3404 0.2551 0.9593

b(:,:,2) =

0.5472 0.8407 0.9293


0.1386 0.2543 0.3500
0.1493 0.8143 0.1966
0.2575 0.2435 0.2511

 We can also use the cat ( ) function to build multidimensional arrays. It concatenates a
list of arrays along a specified dimension:

B = cat (dim, A1, A2...)


Where,
(a) B is the new array created.
(b) A1, A2, ... are the arrays to be concatenated.
(c) dim is the dimension along which to concatenate the arrays.
Example:

a = [9 8 7; 6 5 4; 3 2 1];
b = [1 2 3; 4 5 6; 7 8 9];
c = cat (3, a, b, [2 3 1; 4 7 8; 3 9 0] )

c(:,:,1) =

9 8 7
6 5 4
3 2 1

c(:,:,2) =

1 2 3
4 5 6
7 8 9

c(:,:,3) =

2 3 1
4 7 8
3 9 0

10. Norm:
The norm function calculates several different types of matrix and vector norms. If the input
is a vector or a matrix:
(a) n = norm(X,2) returns the 2-norm of X.
(b) n = norm(X) is the same as n = norm (X,2). n = norm (X,1) returns the 1-norm of X.
(c) n = norm (X, Inf) returns the infinity norm of X.

11. Cell Array:


 Cell arrays are arrays of indexed cells where each cell can store an array of a different
dimension and data type. The cell function is used for creating a cell array. Syntax for
the cell function is:

C = cell (dim) C = cell (dim1, ..., dimN) D = cell(obj) Where,


(i) C is the cell array.
(ii) dim is a scalar integer or vector of integers that specifies the dimensions of cell array C.
(iii) dim1, ... , dimN are scalar integers that specify the dimensions of C.
(iv) obj is one of the following:
java array or object
.Net array of type system string or system object
Example:

c = cell (2, 5);


c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5}

c =

2×5 cell array

{'Red'} {'Blue'} {'Green'} {'Yellow'} {'White'}


{[ 1]} {[ 2]} {[ 3]} {[ 4]} {[ 5]}

12. Accessing Data in Cell Arrays:


 There are two ways to refer to the elements of a cell array:
(1) Enclosing the indices in first bracket (), to refer to sets of cells.
(2) Enclosing the indices in braces {}, to refer to the data within individual cells When
you enclose the indices in first bracket, it refers to the set of cells.
(3) Cell array indices in smooth parentheses refer to sets of cells.

Example:

c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5};


c (1:2, 1:2)

ans =

2×2 cell array

{'Red'} {'Blue'}
{[ 1]} {[ 2]}

You can also access the contents of cells by indexing with curly braces.

c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5};


c{1, 2:4}

ans =

'Blue'

ans =

'Green'

ans =

'Yellow'

Assignments: Write a MATLAB script


1. Ask the user to enter a 3x3 matrix. Upon successful user input display the user
inputted matrix. Return the following result to the user.

a. Minimum of the matrix


b. Maximum of the matrix
c. Transpose of the input matrix
d. Product of the input matrix and its transpose
e. Rank of the Input matrix
f. Infinity norm of the matrix

2. Make a list to keep following student information: name, age, exam-score

Name age score

AA 5 30
BB 6 55
CC 7 70
DD 3 55
EE 6 25
FF 9 38
RF 10 40
QA 5 62
WA 5.5 48
AW 4 56
AZ 6 80

3. Assume the above list (in Q2) available in the computer memory. Now find
through brief program from the list

(i) age of the maximum scorer.

(ii) Print data of the students whose age>=5.

CHAPTER-3
1. Loops:

 There may be a situation when you need to execute a block of code several number
of times. In general, statements are executed sequentially. The first statement in a
function is executed first, followed by the second, and so on.
 Programming languages provide various control structures that allow for more
complicated execution paths.
 A loop statement allows us to execute a statement or group of statements multiple
times and following is the general form of a loop statement in most of the
programming languages:
MATLAB provides following types of loops to handle looping requirements. Click
the following links to check their detail:

(a) Loop Type Description

while loop Repeats a statement or group of statements


while a given condition is true. It tests the
condition before executing the loop body

for loop Executes a sequence of statements multiple


times and abbreviates the code that manages
the loop variable.

nested loops You can use one or more loops inside any
another loop.
While loop:

 The while loop repeatedly executes statements while condition is true.


Syntax:
The syntax of a while loop in MATLAB is:
while
<expressio>
<statement >
end
 The while loop repeatedly executes program statement(s) as long as the expression
remains true.
 An expression is true when the result is nonempty and contains all nonzero elements
(logical or real numeric). Otherwise, the expression is false.
 The while loop repeatedly executes program statement(s) as long as the expression
remains true.
 An expression is true when the result is nonempty and contains all nonzero elements
(logical or real numeric). Otherwise, the expression is false.

Example:
Create a script file and type the following code:

a = 10;
while (a<20)
fprintf ('value of a: %d\n', a);
a=a+1;
end

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

(b) for loop:


A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
Syntax:
The syntax of a while loop in MATLAB is:
for index = values
<programstatements>
End

Example:
Create a script file and type the following code:

for a = 10:20
fprintf ('value of a: %d\n', a);
end

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20

Example:
Create a script file and type the following code:

for a = 1.0: -0.1: 0.0


disp(a)
end

0.9000

0.8000

0.7000

0.6000

0.5000

0.4000

0.3000

0.2000

0.1000

Example:
Create a script file and type the following code:

for a = [24,18,17,23,28]
disp(a)
end

24

18
17

23

28

(c) Nested loops:


MATLAB allows using one loop inside another loop. Following section shows few examples
to illustrate the concept.

Syntax:
The syntax for a nested for loop statement in MATLAB is as follows:
for m = 1:j
for n = 1:k
<statements>;
end
end
The syntax for a nested while loop statement in MATLAB is as follows:
while <expression1>
while <expression2>
<statements>
end
end
Example:
Let us use a nested for loop to display all the prime numbers from 1 to 100. Create a script
file and type the following code:

for i=2:100
for j=2:100
if (~mod(i,j))
break; % if factor found, not prime
end
end
if(j > (i/j))
fprintf('%d is prime\n', i);
end
end

2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime

(2) Loop Control Statements:


Loop control statements change execution from its normal sequence. When execution leaves
a scope, all automatic objects that were created in that scope are destroyed.

MATLAB supports the following control statements. Click the following links to check their
detail.

Control Statement Description

break statement Terminates the loop statement and


transfers execution to the statement
immediately following the loop.

continue statement Causes the loop to skip the remainder of


its body and immediately retest its
condition prior to reiterating.

(a) break statement:

 The break statement terminates execution of for or while loop. Statements in


the loop that appear after the break statement are not executed.
 In nested loops, break exits only from the loop in which it occurs. Control
passes to the statement following the end of that loop.
Flow Diagram:

Example:
Create a script file and type the following code:

a = 10; %while loop execution


while (a < 20 )
fprintf('value of a: %d\n', a); a = a+1;
if( a > 15) %terminate the loop using break statement break;
end
end

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15

(b) Continue statement:


 The continue statement is used for passing control to next iteration of for or while
loop.
 The continue statement in MATLAB works somewhat like the break statement.
Instead of forcing termination, however, 'continue' forces the next iteration of the loop
to take place, skipping any code in between.

Flow Diagram:
Example:
Create a script file and type the following code:

a = 10; %while loop execution


while a < 20
if a == 15 % skip the iteration
a = a + 1;
continue;
end
fprintf('value of a: %d\n', a);
a = a + 1;
end

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Assignments:
1. Write a MATLAB script to create a 4x3 Identity Matrix.
(a) Use a for loop to iterate through each column ix and display them as unit vector.
(b) Use a while loop to do the same as above.
2. Write a MATLAB script to create a Hilbert matrix of the fifth order using for loops.
Hint: A Hilbert matrix of the third order is given as follows.
� 1 1�
1
� 2 3�
� �
1 1 1�
H =�

2 3 4�
� �
1
� 1 1�

3 4 5�

3. Write a MATLAB script to ask the user to input a value between 1 and 10. If the
user enters a number between 1 and 10, the script should display it. If the number does
not lie between 1 and 10 then ask the user to input the number again. Use while loop.

CHAPTER-4
Basic Control commands:
(a) Tf: Create transfer function model, convert to transfer function model.

Example:
s +1
G ( s) =
s + 2s + 1
2

num=[1 1];
den=[1 2 1];
G=tf(num,den)
G=

s+1
-------------
s^2 + 2 s + 1

Continuous-time transfer function.

(b) Tfdata:

[num, den] = tfdata (sys) returns the numerator(s) and denominator(s) of the transfer function
for the TF, SS or ZPK model (or LTI array of TF, SS or ZPK models) sys.

num=[1 1];
den=[1 2 1];
G=tf(num,den)
[num,den]=tfdata(G,'v')

G=

s+1
-------------
s^2 + 2 s + 1

Continuous-time transfer function.

num =

0 1 1

den =

1 2 1

(c) ZPK:

 Used zpk to create zero-pole-gain models (zpk model objects), or to convert dynamic
system to zero-pole-gain model.
 Creates a continuous-time zero-pole-gain model with zeros z, poles p, and gain(s) k.
The output sys is a zpk model object storing the model data.

Example:

Create the continuous-time SISO transfer function:

-2 s
h( s) =
( s -1 + j ) ( s -1 - j ) ( s - 2)
Create h(s) as a zpk object using:

h = zpk(0, [1-i 1+i 2], -2)

h=

-2s
--------------------
(s-2)(s^2-2s+2)

Continuous-time zero/pole/gain model.

(d) Zpkdata:

 [z,p,k] = zpkdata(sys) returns the zeros z, poles p, and gain(s) k of the zero-pole-gain
model sys.
 The outputs z and p are cell arrays with the following characteristics: z and p have as
many rows as outputs and as many columns as inputs.

Example:

H = zpk({[0];[-0.5]},{[0.3];[0.1+i 0.1-i]},[1;2],-1)

H=

from input to output...


z
1: -------
(z-0.3)

2 (z+0.5)
2: -------------------
(z^2 - 0.2z + 1.01)

Sample time: unspecified


Discrete-time zero/pole/gain model.

[z,p,k] = zpkdata(H)

z=

2×1 cell array

{[ 0]}
{[-0.5000]}

p=

2×1 cell array

{[ 0.3000]}
{2×1 double}

k=

1
2

(e) Feedback:
 sys = feedback(sys1,sys2) returns a model object sys for the negative feedback
interconnection of model objects sys1 and sys2.

 The closed-loop model sys has u as input vector and y as output vector. The models
sys1 and sys2 must be both continuous or both discrete with identical sample times.
 To apply positive feedback, use the syntax.
sys = feedback(sys1,sys2,+1)
 By default, feedback(sys1,sys2) assumes negative feedback and is equivalent to
feedback(sys1,sys2,-1).

Example:

To connect the plant


2 s 2 + 5s + 1
G ( s) = 2
s + 2s + 3

With the controller


5( s + 2)
H ( s) =
s + 10
Using negative feedback, type

G = tf([2 5 1],[1 2 3],'inputname','torque','outputname','velocity');


H = zpk(-2,-10,5)
Cloop = feedback(G,H)

H=

5 (s+2)
-------
(s+10)

Continuous-time zero/pole/gain model.

Cloop =

from input "torque" to output "velocity":

0.18182 (s+10) (s+2.281) (s+0.2192)


-----------------------------------
(s+3.419) (s^2 + 1.763s + 1.064)

Continuous-time zero/pole/gain model.

The result is a zero-pole-gain model as expected from the precedence rules. Note that Cloop
inherited the input and output names from G.

(f) Rlocus:
rlocus computes the root locus of a SISO open-loop model. The root locus gives the closed-
loop pole trajectories as a function of the feedback gain k (assuming negative feedback).
Examples:
Plot the root-locus of the following system.

2 s 2 + 5s + 1
h( s) =
s 2 + 2s + 3

h = tf([2 5 1],[1 2 3]);


rlocus(h)

(f) Bode:
 bode(sys) creates a Bode plot of the frequency response of a dynamic system model
sys.
 The plot displays the magnitude (in dB) and phase (in degrees) of the system response
as a function of frequency.

Examples:

Create Bode plot of the dynamic system:


s 2 + 0.1s + 7.5
H ( s) = 4
s + 0.12 s 3 + 9 s 2
H(s) is a continuous-time SISO system.

H = tf([1 0.1 7.5],[1 0.12 9 0 0]);


bode(H)

(g) Nyquist:
nyquist creates a Nyquist plot of the frequency response of a dynamic system model. Nyquist
plots are used to analyze system properties including gain margin, phase margin, and stability.

Example:
Nyquist Plot of Dynamic System Plot the Nyquist response of the system

2 s 2 + 5s + 1
H ( s) =
s 2 + 2s + 3
H = tf([2 5 1],[1 2 3])
nyquist(H)

H=

2 s^2 + 5 s + 1
---------------
s^2 + 2 s + 3

Continuous-time transfer function.

(h) Margin:
margin calculates the minimum gain margin, Gm, phase margin, Pm, and associated
crossover frequencies Wg and Wp of SISO open-loop models. The gain and phase margin of
a system sys indicates the relative stability of the closed-loop system formed by applying unit
negative feedback to sys, as in the following illustration.

The gain margin is the amount of gain increase or decrease required to make the loop gain
unity at the frequency where the phase angle is –180° (modulo 360°). In other words, the gain
margin is 1/g if g is the gain at the –180° phase frequency. Similarly, the phase margin is the
difference between the phase of the response and –180° when the loop gain is 1.0. The
frequency at which the magnitude is 1.0 is called the unity-gain frequency or gain crossover
frequency. It is generally found that gain margins of three or more combined with phase
margins between 30 and 60 degrees result in reasonable trade-offs between bandwidth and
stability.

Example:
Create an open-loop discrete-time transfer function.
hd = tf([0.04798 0.0464],[1 -1.81 0.9048],0.1)
[Gm,Pm,Wg,Wp] = margin(hd)
margin(hd)

hd =

0.04798 z + 0.0464
---------------------
z^2 - 1.81 z + 0.9048

Sample time: 0.1 seconds


Discrete-time transfer function.

Gm =

2.0517

Pm =

13.5711

Wg =

5.4374

Wp =

4.3544
(i) Step:
step calculates the step response of a dynamic system.

Example:
Plot the step response of the following second-order state-space model.

a = [-0.5572 -0.7814;0.7814 0];


b = [1 -1;0 2];
c = [1.9691 6.4493];
sys = ss(a,b,c,0);
step(sys)
(j) Impulse:
impulse calculates the unit impulse response of a dynamic system model.

Example:
Plot the impulse response of the second-order state-space model

use the following commands.

a = [-0.5572 -0.7814 ; 0.7814 0];


b = [1 -1;0 2];
c = [1.9691 6.4493];
sys = ss(a,b,c,0);
impulse(sys)
(k) Lsim:
‘lsim’ simulates the (time) response of continuous or discrete linear systems to arbitrary
inputs.

Example:

H = tf([2 5 1],[1 2 3]);


[u,t] = gensig('square',4,10,0.1);
lsim(H,u,t)
(l) Ss:
Use ss to create state-space models (ss model objects) with real- or complex-valued matrices
or to convert dynamic system models to state-space model form.

>>sys = ss(a,b,c,d), creates a state-space model object representing the continuous-time state-
space model.

For a model with Nx states, Ny outputs, and Nu inputs:


a is an Nx-by-Nx real-or complex-valued matrix.
b is an Nx-by-Nu real- or complex-valued matrix.
c is an Ny-by-Nx real-or complex-valued matrix.
d is an Ny-by-Nu real-or complex-valued matrix.

Example:
Create a state-space model with the following state-space matrices:

To do this, enter the following commands:


A = [0 1;-5 -2];
B = [0;3];
C = [0 1];
D = 0;
sys=ss(A,B,C,D)

sys =

A=
x1 x2
x1 0 1
x2 -5 -2

B=
u1
x1 0
x2 3

C=
x1 x2
y1 0 1
D=
u1
y1 0

Continuous-time state-space model.

(m) Tf2ss:

Convert transfer function filter parameters to state-space form Syntax [A,B,C,D]=tf2ss(b,a).

Example:
To convert this system to state-space, type

b = [0 2 3];
a = [1 0.4 1];
[A,B,C,D] = tf2ss(b,a)

A=

-0.4000 -1.0000
1.0000 0

B=

1
0

C=

2 3

D= 0
(n) Ctrb:
ctrb computes the controllability matrix for state-space systems. For an n-by-n matrix A and
an n-by-m matrix B,
>>ctrb(A,B) returns the controllability matrix (2-1).

Where Co has n rows and nm columns.

Examples:

Check if the system with the following data

A=[1 1;4 -2]


B=[1 -1;1 -1]
Co=ctrb(A,B)
unco=length(A)-rank(Co)

A=

1 1
4 -2

B=

1 -1
1 -1

Co =

1 -1 2 -2
1 -1 2 -2

unco =

(o) Obsv:
obsv computes the observability matrix for state-space systems. For an n-by-n matrix A and a
p-by-n matrix C, obsv(A,C) returns the observability matrix with n columns and np rows.
Example:

A=[1 1;4 -2]


B=[1 -1;1 -1]
Ob=obsv(A,B)
unob=length(A)-rank(Ob)

A=

1 1
4 -2

B=

1 -1
1 -1

Ob =

1 -1
1 -1
-3 3
-3 3

unob =

1
CHAPTER-5

PID Control Design by the analysis of Root-Locus using


SISOTOOL

Another way to complete what was done above is to use the interactive MATLAB GUI called
‘sisotool’. Using the same model as above, first define the plant, H(s).
The ‘sisotool’ function can be used for analysis and design. In this case, we will focus on
using the Root Locus as the design method to improve the step response of the plant. To
begin, type the following into the MATLAB command window:

s = tf('s');
plant = (s + 7)/(s*(s + 5)*(s + 15)*(s + 20))
sisotool (plant)

The following window should appear. To start, select the tab labeled Graphical Tuning.
Within this window, turn off Plot 2 and make sure Plot 1 is the Root Locus and verify that
Open Loop 1 is selected. Finally, click the button labeled how Design Plot to bring up the
tunable Root Locus plot.
In the same fashion, select the tab labeled Analysis Plots. Within this window, for Plot 1,
select Step. In the Contents of Plots sub window, select Closed Loop r to y for Plot 1. If the
window does not automatically pop up, click the button labeled Show Analysis Plot.
How Design Plot to bring up the tunable Root Locus plot.
In the same fashion, select the tab labeled Analysis Plots. Within this window, for Plot 1,
select Step. In the Contents of Plots sub window, select Closed Loop r to y for Plot 1. If the
window does not automatically pop up, click the button labeled Show Analysis Plot.

The next thing to do is to add the design requirements to the Root Locus plot. This is done
directly on the plot by right-clicking and selecting Design Requirements, New. Design
requirements can be set for the Settling Time, the Percent Overshoot, the Damping Ratio, the
Natural Frequency, or a Region Constraint. There is no direct requirement for Rise Time, but
the natural frequency can be used for this.
Here, we will set the design requirements for the damping ratio and the natural frequency just
like was done with ‘sgrid’. Recall that the requirements call for ζ= 0.7 and ωn= 1.8. Set these
within the design requirements. On the plot, any area which is still white, is an acceptable
region for the poles.
Zoom into the Root Locus by right-clicking on the axis and select Properties, then click the
label Limits. Change the real axis to -25 to 5 and the imaginary to -2.5 to 2.5.
Also, we can see the current values of some key parameters in the response. In the Step
response, right-click on the plot and go to Characteristics and select Peak Response. Do the
same for the Rise Time. There should now be two large dots on the screen indicating the
location of these parameters. Click each of these dots to bring up a screen with information.

Both plots should appear as shown here:


As the characteristics show on the Step response, the overshoot is acceptable, but the rise
time is incredibly off. To fix this, we need to choose a new value for the gain K. Similarly to
the ‘rlocfind’ command, the gain of the controller can be changed directly on the root locus
plot. Click and drag the pink box on the origin to the acceptable area where the poles have an
imaginary component as shown below.

At the bottom of the plot, it can be seen that the loop gain has been changed to 361. Looking
at the Step response, both of the values are acceptable for our requirements.
Example

Find out the (1) PID controller parameters for the below mentioned plant from root-locus
graph by utilizing the SISO Tool and (2) by employing these obtained parameter values
design a PID controller for the plant

-0.03607 s + 0.0009356
1. T1 =
s + 0.09086s + 0.0001558
2

-2 s + 6
2. T2 =
s + 7s + 5
2
CHAPTER-6

Graphics:-

 MATLAB includes good tools for visualization. Basic 2-D plots, fancy 3-D graphics
with lighting and color-maps, complete user-control of the graphics objects through
Handle Graphics, tools for design of sophisticated graphics user-interface, and
animation are now part of MATLAB. What is special about MATLAB’s graphics
facility is its ease of use and expandability. Commands for most garden-variety
plotting are simple, easy to use, and intuitive. If you are not satisfied with what you
get, you can control and manipulate virtually everything in the graphics window. This,
however, requires an understanding of the Handle Graphics, a system of low-level
functions to manipulate graphics objects. In this section we take you through the main
features of the MATLAB’s graphics facilities.
Basic 2-D Plots:

 The most basic and perhaps the most useful command for producing a simple 2-D plot
is
>> plot(xvalues, yvalues,’style-option’)
 where ‘xvalues’ and ‘yvalues’ are vectors containing the x- and y-coordinates of
points on the graph and the style-option is an optional argument that specifies the
color, the line style (e.g. solid, dashed, dotted, etc.), and the point-marker style (e.g. o,
+, *, etc.). All the three options can be specified together as the style-option in the
general form:
color_ linestyle_markerstyle
 The two vectors xvalues and yvalues MUST have the same length. Unequal length of
the two vectors is the most common source of error in the plot command. The plot
function also works with a single vector argument, in which case the elements of the
vector are plotted against row or column indices. Thus, for two column vectors x and
y each of length n,

plot(x,y) plots y vs. x with a solid line (the default line style),
plot(x,y,’--’) plots y vs. x with a dashed line (more on this below),
plot(x) plots the elements of x against their row index.

Style options:

 The style-option in the plot command is a character string that consists of 1, 2, or 3


characters that specify the color and/or the line style. There are several color, line-
style, and marker-style options:

 The style-option is made up of the color option, the line-style option, or a combination
of the two.

Examples:
plot(x,y,’r’) plots y vs. x with a red solid line,
plot(x,y,’:’) plots y vs. x with a dotted line,
plot(x,y,’b--’) plots y vs. x with a blue dashed line,
plot(x,y,’+’) plots y vs. x as unconnected points marked by+.
 When no style option is specified, MATLAB uses the default option a blue solid line.

Labels, title, legend, and other text objects:

 Plots may be annotated with xlabel, ylabel, title, and text commands.
 The first three commands take string arguments, while the last one requires three
arguments- text(x-coordinate, y-coordinate, ’text’), where the coordinate values are
taken from the current plot. Thus,

xlabel(’Pipe Length’) labels the x-axis with Pipe Length,


ylabel(’Fluid Pressure’) labels the y-axis with Fluid Pressure,
title(’Pressure Variation’) titles the plot with Pressure Variation,
text(2,6,’Note this dip’) writes ‘Note this dip’ at the location

(2.0,6.0) in the plot coordinates.

 We have already seen an example of xlabel, ylabel, and title in Fig. 3.10. An example
of text appears in Fig. 6.2. The arguments of help graph2d text(x,y,’text’) command
may be vectors, in which case x and y must have the same length and text may be just
one string or a vector of strings. If text is a vector then it must have the same length as
x and, of course, like any other string vector, must have each element of the same
length. A useful variant of the text command is ‘gtext’, which only takes string
argument (a single string or a vector of strings) and lets the user specify the location
of the text by clicking the mouse at the desired location in the graphics window.

Legend:
 The legend command produces a boxed legend on a plot, as shown, for example, in
Fig. 6.3 on page 166. The legend command is quite versatile. It can take several
optional arguments. The most commonly used forms of the command are listed
below.
legend(string1, string2, ..) produces legend using the text in
string1, string2, etc. as labels.

legend(LineStyle1, string1, ..) specifies the line-style of each label.

legend(.., pos) writes the legend outside the plot-


frame if pos = -1 and inside the
frame if pos = 0.
(There are other options for pos too.)

legend off deletes the legend from the plot.

 When MATLAB is asked to produce a legend, it tries to find a place on the plot where
it can write the specified legend without running into lines, grid, and other graphics
objects. The optional argument pos specifies the location of the legend box. pos=1
places the legend in the upper right hand corner (default), 2 in the upper left hand
corner, 3 in the lower left hand corner, and 4 in the lower right hand corner. The user,
however, can move the legend at will with the mouse (click and drag). For more
information, see the on-line help on legend.
Axis control, zoom-in, and zoom-out:

 Once a plot is generated you can change the axes limits with the axis command.
Typing
>> axis([xmin xmax ymin ymax])

changes the current axes limits to the specified new values xmin and xmax for the x-
axis and ymin and ymax for the y-axis.

Examples:

axis([-5 10 2 22]); sets the x-axis from −5 to 10, y-axis from 2 to 22.

axy = [-5 10 2 22]; axis(axy); same as above. ax = [-5 10]; ay = [2 22];

axis([ax ay]); same as above.

 The axis command may thus be used to zoom-in on a particular section of the plot or
to zoom-out1. There are also some useful predefined string arguments for the axis
command:
axis(’equal’) sets equal scale on both axes

axis(’square’) sets the default rectangular frame to a square

axis(’normal’) resets the axis to default values axis(’axis’)


freezes the current axes limits

axis(’off’) removes the surrounding frame and the tick mark

 The axis command must come after the plot command to have the desired
effect.

Semi-control of axes :
It is possible to control only part of the axes limits and let MATLAB set the other limits
automatically. This is achieved by specifying the desired limits in the axis command along
with inf as the values of the limits which you would like to be set automatically.

Example :

axis([-5 10 -inf inf]) sets the x-axis limits at −5 and 10 and lets
the y-axis limits be set automatically.

axis([-5 inf -inf 22]) sets the lower limit of the x-axis and the
upper limit of the y-axis, and leaves the
other two limits to be set automatically.
Modifying plots with Plot Editor:
 MATLAB 6 provides an enhanced (over previous versions) interactive tool for
modifying an existing plot. To activate this tool, go to the Figure window and click on
the left-leaning arrow in the menu bar (see Fig. 6.1). Now you can select and double
(or right) click on any object in the current plot to edit it. Double clicking on the
selected object brings up a Property Editor window where you can select and modify
the current properties of the object. Other tools in the menu bar, e.g., text (marked by
A), arrow, and line, lets you modify and annotate figures just like simple graphics
packages do.

 MATLAB provides interactive plot editing tools in the Figure window menu bar.
Select the first arrow (left-leaning) for activating plot editor. Select A, the right-
leaning arrow, and the diagonal line for adding text, arrows, and lines, respectively, in
the current plot.

Set:
Set Handle Graphics object properties.
Syntax :
set(H,'PropertyName',PropertyValue,...)
set(H,a)
set(H,pn,pv,...)
set(H,pn,MxN_pv)
a = set(h)
pv = set(h,'PropertyName')

Description:

 set(H,'PropertyName',’PropertyValue’,...) sets the named properties to the specified


values on the object(s) identified by H. H can be a vector of handles, in which case set
sets the properties' values for all the objects.
 set(H,a) sets the named properties to the specified values on the object(s) identified by
H. a is a structure array whose field names are the object property names and whose
field values are the values of the corresponding properties.
 set(H,pn,pv,...) sets the named properties specified in the cell array pn to the
corresponding value in the cell array pv for all objects identified in H.
• set(H,pn,MxN_pv) sets n property values on each of m graphics objects, where m =
length(H) and n is equal to the number of property names contained in the cell array pn.
This allows you to set a given group of properties to different values on each object.

 a = set(h) returns the user-settable properties and possible values for the object
identified by h. a is a structure array whose field names are the object's property
names and whose field values are the possible values of the corresponding properties.
If you do not specify an output argument, the MATLAB software displays the
information on the screen. h must be scalar.
 pv = set(h,'PropertyName') returns the possible values for the named property. If the
possible values are strings, set returns each in a cell of the cell array pv. For other
properties, set returns a statement indicating that PropertyName does not have a fixed
set of property values. If you do not specify an output argument, MATLAB displays
the information on the screen. h must be scalar.

Examples:
• Set the Color property of the current axes to blue. axes;
set(gca,'Color','b')
• Change all the lines in a plot to black. plot(peaks)
set(findobj('Type','line'),'Color','k')
• Setting Different Values for the Same Property on Multiple Objects. Suppose you
want to set the value of the Tag property on five line objects, each to a different value.
h = plot(rand(5));
set(h,{'Tag'},{'line1','line2','line3','line4','line5'}')

Overlay plots:

There are three different ways of generating overlay plots in MATLAB: the plot, hold, and
line commands.

Method-1: Using the plot command to generate overlay plots:

 If the entire set of data is available, plot command with multiple arguments may be
used to generate an overlay plot. For example, if we have three sets of data— (x1,y1),
(x2,y2), and (x3,y3)—the command plot(x1,y1, x2,y2,’:’, x3,y3,’o’) plots (x1,y1)
with a solid line, (x2,y2) with a dotted line, and (x3,y3) as unconnected points marked
by small circles (’o’), all on the same graph (See Fig. 6.2 for example). Note that the
vectors (xi,yi) must have the same length pairwise. If the length of all vectors is the
same, then it is convenient to make a matrix of x vectors and a matrix of y vectors and
then use the two matrices as the argument of the plot command. For example, if x1,
y1, x2, y2, x3, and y3 are all column vectors of length n then typing X=[x1x2 x3];
Y=[y1y2 y3]; plot(X,Y) produces a plot with three lines drawn in different colors.
When plot command is used with matrix arguments, each column of the second
argument matrix is plotted against the corresponding column of the first argument
matrix.
t=linspace(0,2*pi,100);
y1=sin(t);
y2=t;
y3=t-(t.^3)/6+(t.^5)/120;
plot(t,y1,t,y2,'--',t,y3,'o')
axis([0 5 -1 5])
xlabel('t')
ylabel('Approximations of sin(t)')
title('Fun with sin(t)')
text(3.5,0,'sin(t)')
gtext('Linear approximation')
gtext('First 3 terms')
gtext('in Taylor series')

Example of an overlay plot along with examples of xlabel, ylabel, title, axis, text, and gtext
commands. The three lines plotted are y1=sint, y2=t, y3=t-t2/3!-t5/5!
Method-2: Using the hold command to generate overlay plots:

 Another way of making overlay plots is with the hold command. Invoking hold on at
any point during a session freezes the current plot in the graphics window. All
subsequent plots generated by the plot command are simply added to the existing plot.
The following script file shows how to generate the same plot as in above figure by
using the hold command.
x=linspace(0,2*pi,100);
y1=sin(x);
y2=x;
y3=x-(x.^3)/6+(x.^5)/120;
plot(x,y1)
hold on;
plot(x,y2,'--')
plot(x,y3,'o')
axis([0 5 -15 15])
hold off

 The hold command is useful for overlay plots when the entire data set to be plotted is
not available at the same time. You should use this command if you want to keep
adding plots as the data becomes available. For example, if a set of calculations done
in a for loop generates vectors x and y at the end of each loop and you would like to
plot them on the same graph, hold is the way to do it.

Method-3: Using the line command to generate overlay plots:

 The line is a low-level graphics command which is used by the plot command to
generate lines. Once a plot exists in the graphics window, additional lines may be
added by using the line command directly. The line command takes a pair of vectors
(or a triplet in 3-D) followed by parameter name/parameter value pairs as arguments:
line(xdata, ydata, ParameterName, ParameterValue)
 This command simply adds lines to the existing axes. For example, the overlay plot
created by the above script file could also be created with the following script file,
which uses the line command instead of the hold command. As a bonus to the reader,
we include an example of the legend Command.
 % -- Script file to generate an overlay plot with the line command –
t=linspace(0,2*pi,100);
y1=sin(t);
y2=t;
y3=t-(t.^3)/6+(t.^5)/120;
plot(t,y1)
line(t,y2,'linestyle','--')
line(t,y3,'marker','o')
axis([0 5 -15 5])
xlabel('t')
ylabel('Approximations of sin(t)')
title('Fun with sin(t)')
legend('sin(t)','linear approx.','5th order approx.')
 The output generated by the above script file is shown in Figure. After generating the
plot, click and hold the mouse on the legend rectangle and see if you can drag the
legend to some other position. Alternatively, you could specify an option in the legend
command to place the legend rectangle in any of the four corners of the plot. See the
on-line help on legend.
Example of an overlay plot produced by using the line command.The legend is produced by
the legend command. See the script file for details.

Specialized 2-D plots:

 There are many specialized graphics functions for 2-D plotting. They are used as
alternatives to the plot command we have just discussed. There is a whole suite of
ezplotter functions, such as ezplot, ezpolar, ezcontour, etc., which are truly easy to
use. See Section 3.6 for a discussion and examples of these functions.
Here, we provide a list of other functions commonly used for plotting:

x-y data: area creates a filled area


plot bar: creates a bar graph
barh: creates a horizontal bar graph
comet : makes an animated 2-D plot
compass: creates arrow graph for complex numbers
contour: makes contour plots
contour: makes filled contour plots
errorbar : plots a graph and puts error bars
feather: makes a feather plot
fill : draws filled polygons of specified color
fplot : plots a function of a single variable
hist : makes histograms
loglog: creates plot with log scale on both x and y axes
pareto : makes pare to plots
pcolor : makes pseudo color plot of a matrix
pie : creates a pie chart
plotyy: makes a double y-axis plot
plotmatrix: makes a scatter plot of a matrix

 On the following pages we show examples of these functions. The commands shown
in the middle column produce the plots shown in the right column. There are several
ways you can use these graphics functions. Also, many of them take optional
arguments. The following examples should give you a basic idea of how to use these
functions and what kind of plot to expect from them. For more information on any of
these functions see the on-line help.

Example of some MATLAB function:

(a) fplot:

x=linspace(0,2*pi,100);
fplot('x.*sin(x)',[0 10*pi])
(b) semilogx:

t=linspace(0,2*pi,100);
x=exp(-t);y=t;
semilogx(x,y)
grid on;

(c) semilogy:
t=linspace(0,2*pi,100);
semilogy(t,exp(t))
grid on;
(d) loglog:

t=linspace(0,2*pi,100);
x=exp(t);
y=100+exp(2*t);
loglog(x,y)
grid on;

(e) polar:
t=linspace(0,2*pi,100);
r=sqrt(abs(2*sin(5*t)));
polar(t,r)
(f) fill:

t=linspace(0,2*pi,100);
r=sqrt(abs(2*sin(5*t)));
x=r.*cos(t);
y=r.*sin(t);
fill(x,y,'k')
axis('square')

(g) errorbar:

x=0:0.1:2;
apprx2=x-x.^3/6;
er=apprx2-sin(x);
errorbar(x,apprx2,er)
(h) Barh:

cont=char('asia','europe','africa');
pop=[3332;696;694];
barh(pop)
for i=1:3
gtext(cont(i,:));
end
xlabel('population in millions')

(i) plotyy:

x=1:0.1:10;
y1=exp(-x).*sin(x);
y2=exp(x);
Ax=plotyy(x,y1,x,y2);
hy1=get(Ax(1),'ylabel');
hy2=get(Ax(2),'ylabel');
set(hy1,'string','e^-x sin(x)');
set(hy1,'string','e^x');
(j) area:

x=linspace(-3*pi,3*pi,100);
y=-sin(x)./x;
area(x,y)
xlabel('x')
ylabel('sin(x)./x')
hold on;
x1=x(46:55);y1=y(46:55);
area(x1,y1,'facecolor','y')
(k) pie:

cont=char('asia','europe','africa');
pop=[3332;696;694];
pie(pop)
for i=1:3
gtext(cont(i,:));
end
xlabel('population in millions')

(l) hist:

y=randn(50,1);
hist(y)
(m) stem:

t=linspace(0,2*pi,200);
f=exp(-.2*t).*sin(t);
stem(t,f)

(n) stairs:

t=linspace(0,2*pi,200);
r=sqrt(abs(2*sin(5*t)));
y=r.*sin(t);
stairs(t,y)
axis([0 pi 0 inf])
(o) compass:

th=-pi:pi/5:pi;
zx=cos(th);
zy=sin(th);
z=zx+i*zy;
compass(z)

(p) comet:

q=linspace(0,10*pi,200);
y=q.*sin(q);
comet(q,y)
(q) contour:

r=-5:0.2:5;
[x,y]=meshgrid(r,r);
z=-0.5*x.^2+x.*y+y.^2;
cs=contour(x,y,z);
clabel(cs)

(r) quiver:

r=-2:0.2:2;
[x,y]=meshgrid(r,r);
z=-0.5*x.^2+x.*y+y.^2;
[dx,dy]=gradient(z,.2,.2);
quiver(x,y,dx,dy,2);
(s) pcolor:

r=-2:0.2:2;
[x,y]=meshgrid(r,r);
z=-0.5*x.^2+x.*y+y.^2;
pcolor(z);
axis('off');
shading interp
Using subplot to Layout Multiple Graphs:
 If you want to make a few plots and place the plots side-by-side (not overlay), use the
subplot command to design your layout. The subplot command requires three integer
arguments:
subplot(m,n,p)

 Subplot divides the graphics window into m × n sub-windows and puts the plot
generated by the next plotting command into the pth sub-window where the sub-
windows are counted row-wise. Thus, the command subplot(2,2,3), plot(x,y) divides
the graphics window into 4 sub-windows and plots y vs. x in the 3rd sub-window,
which is the first sub-window in the second row

3-D Plots:
 MATLAB provides extensive facilities for visualization of 3-D data. In fact, the built-
in color maps may be used to represent the 4th dimension. The facilities provided
include built-in functions for plotting space-curves, wireframe objects, surfaces and
shaded surfaces, generating contours automatically, displaying volumetric data,
specifying light sources, interpolating colors and shading, and even displaying
images. Typing help graph3d in the command window gives a list of functions
available for general 3-D graphics. Here is a list of commonly used functions other
than those from the ez-stable, such as ezsurf, ezmesh, ezplot3, etc..

 plot3 plots curves in space


 stem3 creates discrete data plot with stems in 3-D
 bar3 plots 3-D bar graph
 bar3h plots 3-D horizontal bar graph
 pie3 makes 3-D pie chart
 comet3 makes animated 3-D line
 plot fill3 draws filled 3-D polygons
 contour3 makes 3-D contour plots
 quiver3 draws vector fields in 3D
 scatter3 makes scatter plot in 3-D
 mesh draws 3-D mesh surfaces (wire-frame)
 meshc draws 3-D mesh surface along with contours
 meshz draws 3-D mesh surface with curtain plot of reference planes
 surf creates 3-D surface plots
 surfc creates 3-D surface plots along with contours
 surfl creates 3-D surface plots with specified light source
 trimesh mesh plot with triangles
 trisurf surface plot with triangles
 slice draws a volumetric surface with slices waterfall creates a waterfall
plot of 3-D data cylinder generates a cylinder ellipsoid generates an ellipsoid.
 sphere generates a sphere
 Among these functions, plot3 and comet3 are the 3-D analogues of plot and comet
commands mentioned in the 2-D graphics section. The general syntax for the plot3
command is
>> plot3(x, y, z, ’style-option’)

 This command plots a curve in 3-D space with the specified line style. The argument
list can be repeated to make overlay plots, just the same way as with the plot
command. A catalog of these functions with example scripts and the corresponding
output is given on pages 181–185. Since the example scripts use a few functions
which we have not discussed yet, we postpone the catalog till we discuss these
functions.
 Plots in 3-D may be annotated with functions already mentioned for 2-D plots—
xlabel, ylabel, title, text, grid, etc., along with the obvious addition of zlabel. The grid
command in 3-D makes the 3-D appearance of the plots better, especially for curves
in space .

View:
 The viewing angle of the observer is specified by the command.
>>view(azimuth, elevation)

 where azimuth, in degrees, specifies the horizontal rotation from the y-axis, measured
positive counterclockwise, and elevation, in degrees, specifies the vertical angle
measured positive above the xy-plane . The default values for these angles are −37.5o
and 30o respectively.
 By specifying appropriate values of the azimuth and the elevation, one can plot the
projections of a three-dimensional object on different 2-D planes. For example, the
command view(90,0) puts the viewer on the positive xaxis, looking straight on the yz-
plane, and thus produces a 2-D projection of the object on the yz-plane. Figure shows
the projections obtained by specifying view angles. The script file that generates the
data, plots the curves, and obtains the different projected views is listed below.

%--- Script file with examples of ‘subplot’ and ‘view’ commands ---
clf
t=linspace(0,6*pi,100);
x=cos(t); y=sin(t); z=t;
subplot(2,2,1)
plot3(x,y,z)
grid on;
xlabel('cos(t)')
ylabel('sin(t)')
zlabel('t')
title('A circular helix: x(t)=cos(t), y(t)=sin(t), z(t)=t')
subplot(2,2,2)
plot3(x,y,z)
grid on;
view(0,90)
title('Projection in the X-Y plane')
subplot(2,2,3)
plot3(x,y,z)
view(0,0)
title('Projection in the X-Z plane')
subplot(2,2,4)
plot3(x,y,z)
view(90,0)
title('Projection in the Y-Z plane')
View(2) and View(3):

 These are the special cases of the view command, specifying the default 2-D and 3-D
views:
view(2) same as view(0,90), shows the projection in the xz-plane.
view(3) same as view(-37.5,30), shows the default 3-D view.

 The view(3) command can be used to see a 2-D object in 3-D. It may be useful in
visualizing the perspectives of different geometrical shapes. The following script file
draws a filled circle in 2-D and also views the same circle in 3-D. The output is shown
in Figure .

Examples of plot3, subplot and view. Note how the 3-D grid in the background helps in the 3-
D appearance of the space curve. Although the three 2-D pictures could be made using the
plot command, this example illustrates the use of viewing angles.

% ----- script file to draw a filled circle and view in 3D -----

theta = linspace(0,2*pi,100);
x=cos(theta);
y=sin(theta);
subplot(1,2,1)
fill(x,y,'g');
axis('square');
subplot(1,2,2)
fill(x,y,'g');
axis('square');
view(3)

Rotate view :
 MATLAB 5 provides more versatile and easier utilities for manipulating the view
angle of a 3-D plot. There is a simple utility called rotate3d. Simply turn it on with
rotate3d on and rotate the view with your mouse. There are also some sophisticated
camera functions that let you specify the camera view angle, zoom, roll, pan, etc. See
the on-line help on graph3D.

Mesh and surface plots:


 The functions for plotting meshes and surfaces mesh and surf, and their various
variants meshz, meshc, surfc, and surfl, take multiple optional arguments, the most
basic form being mesh(Z) or surf(Z), where Z represents a matrix. Usually surfaces
are represented by the values of z-coordinates sampled on a grid of (x, y) values.
Therefore, to create a surface plot we first need to generate a grid of (x, y) coordinates
and find the height (z coordinate) of the surface at each of the grid points. Note that
you need to do the same thing for plotting a function of two variables. MATLAB
provides a function meshgrid to create a grid of points over a specified range.
 The function meshgrid: Suppose we want to plot a function z = x2 −y2 over the
domain 0 ≤ x ≤ 4 and −4 ≤ y ≤ 4. To do so, we first take several points in the domain,
say 25 points, as shown in Fig. 6.7. We can create two matrices X and Y, each of size
5 × 5, and write the xy-coordinates of each point in these matrices. We can then
evaluate z with the command z = X.^2-Y.^2;. Creating the two matrices X and Y is
much easier with the meshgrid command:
rx=0:4;
ry=-4:2:4;
[x,y]=meshgrid(rx,ry)

x=

0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4

y=

-4 -4 -4 -4 -4
-2 -2 -2 -2 -2
0 0 0 0 0
2 2 2 2 2
4 4 4 4 4

A grid of 25 points in the xy-plane. The grid can be created by the meshgrid command: [X,Y]
= meshgrid(rx,ry); where rx and ry are vectors specifying the location of grid lines along x
and y axes.
 The commands shown above generate the 25 points shown in Figure. All we need to
generate is two vectors, rx and ry, to define the region of interest and distribution of
grid points. Also, the two vectors need not be either same sized or linearly spaced. To
be comfortable with 3-D graphics, you should understand the use of meshgrid.
 Back to mesh plot: When a surface is plotted with mesh(z) (or surf(z)) command,
where z is a matrix, then the tickmarks on the x and y axes do not indicate the domain
of z but the row and column indices of the zmatrix. This is the default. Typing
mesh(x,y,z) or surf(x,y,z), where x and y are vectors used by meshgrid command to
create a grid, results in the surface plot of z with x- and y-values shown on the x and y
axes. The following script file should serve as an example of how to use meshgrid and
mesh command. Here we try to plot the surface

by computing the values of z over a 50 × 50 grid on the specified domain.


The results of the two plot commands are shown in Figure.

x=linspace(-3,3,50);
y=x;
[X,Y]=meshgrid(x,y);
Z=X.*Y.*(X.^2-Y.^2)./(X.^2+Y.^2);
mesh(X,Y,Z)
figure(2)
meshc(X,Y,Z)
view(-55,20)
3-D surface plots created by mesh and meshc commands. The second plot uses a different
viewing angle to show the center of the contour lines. Note that the surfaces do not show
hidden lines (this is the default setting; it can be changed with the hidden command).
 While surfaces created by mesh or its variants have a wire-frame appearance, surfaces
created by the surf command or its variants produce a true surfacelike appearance,
especially when used with the shading command. There are three kinds of shading
available— shading flat produces simple flat shading, shading interp produces more
dramatic interpolated shading, and shading faceted, the default shading, shows shaded
facets of the surface. Both mesh and surf can plot parametric surfaces with color
scaling to indicate a fourth dimension. This is accomplished by giving four matrix
arguments to these commands, e.g. surf(X,Y,Z,C) where X, Y, and Z are matrices
representing a surface in parametric form and C is the matrix indicating color scaling.
The command surfl can be used to control the light reflectance and to produce special
effects with a specified location of a light source. See on line help on surfl for more
information.
 We close this section with a catalog of the popular 3D graphics functions. We hope
that you can use these functions for your needs simply by following the example
scripts. But we acknowledge that the meshgrid command takes some thought to
understand well.

Some other plot functions

(1)

t=linspace(0,1,100);
x=t;y=t.^2;z=t.^3;
plot3(x,y,z)
grid on;
(2)

x=[0 0 0 0;1 1 -1 1;1 -1 -1 -1];


y=[0 0 0 0;4 4 4 4;4 4 4 4];
z=[0 0 0 0;1 1 -1 -1;-1 1 1 -1];
fill3(x,y,z,rand(3,4))
view(120,30)

(3)
(5)

(6)

(7)
Note: Plotting a surface with surf(X,Y,Z) shows proper values on the x and y axes while
plotting the surface with surf(Z) shows the row and column indices of matrix Z on the x and y
axes. Same is true for other 3D plotting commands such as mesh, contour3, etc. Compare the
values on the x and y axes in the first and the last figure in the table above.
Interpolated surface plots:
 Many a times, we get data (usually from experiments) in the form of (x, y, z) triples,
and we want to fit a surface through the data. Thus, we have a vector z that contains
the z-values corresponding to irregularly spaced x and y values. Here, we do not have
a regular grid, as created by meshgrid, and we do not have a matrix Z that contains the
z-values of the surface at those grid points. Therefore, we have to fit a surface through
the given triplets (xi, yi, zi). The task is much simpler than it seems. MATLAB 5
provides a function, griddata that does this interpolation for us. The general syntax of
this function is

>> [Xi,Yi,Zi] = griddata(x,y,z,xi,yi,method)

 where x, y, z are the given data vectors (non-uniformly spaced), xi and yi are the user
prescribed points (hopefully, uniformly spaced) at which zi are computed by
interpolation, and method is the choice for the interpolation algorithms. The
algorithms available are nearest, linear, cubic, and v4. See the on-line documentation
for description of these methods.
 As an example let us consider 50 randomly distributed points in the xyplane, in the
range −1 < x < 1, and −1 < y < 1. Let the z values at these points be given by z = 3/
(1+x2+y2). Thus, we have three vectors of length 50 each. The data points are shown
in Figure by the stem plot. Now, let us fit a surface through these points:
% interpolation to fit a surface through the data %

xv=2*rand(1,100)-1;
yv=2*rand(1,100)-1;
zv=3./(1+xv.^2+yv.^2);
stem3(xv,yv,zv)
xi=linspace(-1,1,30);
yi=xi';
[Xi,Yi,Zi] = griddata(xv,yv,zv,xi,yi,'v4');
surf(Xi,Yi,Zi)

You might also like