Control & Simulation Lab-I Manual: Vector and Matrix
Control & Simulation Lab-I Manual: Vector and Matrix
Control & Simulation Lab-I Manual: Vector and Matrix
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
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
help find
c = [7;8;9;10;11]
c =
7
8
9
10
11
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
c = [7;8;9;10;11]
c =
7
8
9
10
11
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.
7 11 15 23 9
B =
2 5 13 16 20
C =
9 16 28 39 29
D =
5 6 2 7 -11
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.
r = [ 1 2 3 4]
tr = r'
r =
1 2 3 4
tr =
1
2
3
4
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 = [1 2 20];
sv = v.* v;
dp= sum(sv);
mag = sqrt(dp)
mag =
20.1246
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
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
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 :
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:
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
a =
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
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 = [ 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
a = [ 1 2 3 ; 4 5 6; 7 8 9];
b = [ 7 5 6 ; 2 0 8; 5 7 1];
c = a / b
c =
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 =
a = [ 10 12 23 ; 14 8 6; 27 8 9];
b = a'
b =
10 14 27
12 8 8
23 6 9
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
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
a = [ 1 2 3; 2 3 4; 1 2 5];
b = det (a)
b =
-2
a = [ 1 2 3; 2 3 4; 1 2 5];
b = inv (a)
b =
ans =
1
5
9
Example:
A = [1 5 8; 4 5 6; 7 8 9];
trace(A)
ans =
15
A = [6 7 9; 3 4 6; 7 2 3];
rank (A)
ans =
A = [6 7 9; 3 4 6; 7 2 3];
[v, e] = eig (A)
v =
e =
e =
5 12 21 32
f =
5 6 7 8
Assignments:
1 2 3�
� 5 6 7�
�
�
A=� � �
6 7 8�
4 5 6� B = � �
�
6 7 8�
� � � �
7 8 9�
�
(i) ( A �B ) + ( A-1 �B )
(ii) A + ( B �A )
T
5
� 6 7 1�
�
6 7 8 1�
A=� �
�
7 8 9 0�
� �
4
� 5 6 4�
(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 =
Columns 1 through 4
Columns 5 through 6
ans =
Columns 1 through 4
Columns 5 through 6
ans =
Columns 1 through 4
Columns 5 through 6
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:
ans =
Columns 1 through 4
Columns 5 through 6
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
max (X, [ ], 2)
ans =
8
9
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
min (X, [ ], 2)
ans =
2
3
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.
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 =
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) =
b(:,:,2) =
We can also use the cat ( ) function to build multidimensional arrays. It concatenates a
list of arrays along a specified dimension:
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.
c =
Example:
ans =
{'Red'} {'Blue'}
{[ 1]} {[ 2]}
You can also access the contents of cells by indexing with curly braces.
ans =
'Blue'
ans =
'Green'
ans =
'Yellow'
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
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:
nested loops You can use one or more loops inside any
another loop.
While loop:
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
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:
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
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
MATLAB supports the following control statements. Click the following links to check their
detail.
Example:
Create a script file and type the following code:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
Flow Diagram:
Example:
Create a script file and type the following code:
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
(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
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:
-2 s
h( s) =
( s -1 + j ) ( s -1 - j ) ( s - 2)
Create h(s) as a zpk object using:
h=
-2s
--------------------
(s-2)(s^2-2s+2)
(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=
2 (z+0.5)
2: -------------------
(z^2 - 0.2z + 1.01)
[z,p,k] = zpkdata(H)
z=
{[ 0]}
{[-0.5000]}
p=
{[ 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:
H=
5 (s+2)
-------
(s+10)
Cloop =
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
(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:
(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
(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
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.
Example:
Plot the impulse response of the second-order state-space model
Example:
>>sys = ss(a,b,c,d), creates a state-space model object representing the continuous-time state-
space model.
Example:
Create a state-space model with the following state-space matrices:
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
(m) Tf2ss:
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).
Examples:
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 =
1 -1
1 -1
-3 3
-3 3
unob =
1
CHAPTER-5
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.
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 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.
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,
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.
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.
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
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:
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.
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.
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.
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:
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.
(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..
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.
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.
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
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.
(1)
t=linspace(0,1,100);
x=t;y=t.^2;z=t.^3;
plot3(x,y,z)
grid on;
(2)
(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
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)