Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Controlmanual Complte UpdatedwithCLOS (1)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 101

Control Engineering LAB

Assingment

Submitted to:
Engr. Ammad Arshad

Submitted by:
Name: Mohsin Shahzad
(Meen211101082)
(Meen 6B)

INSTITUTE OF MECHANICAL AND MANUFACTURING


ENGINEERING (IMME)
Khwaja Fareed University of Engineering and Information Technology, Rahim Yar
Khan

Control Engineering Lab 1/101


Control Engineering Laboratory (MEEN-3201)
List of Experiments
Lab Sessions
Sr.#
1. Introduction to MATLAB its functions and applications.

2. Introduction to MATLAB its functions and applications


Plotting, Curve Fitting (Part-II)
3. Introduction to MATLAB its functions and applications.
Control Engineering Lab 2/101
Programming, Solution of ODE, Polynomial roots, Partial
Fractions (Part-III)
4. Introduction to some MATLAB’s Control functions.

5. Introduction to some MATLAB’s Control functions.


6. Responses of 1st order and 2nd Order Systems

7. Introduction and Some Basic Application of SIMULINK.


8. Practical Examples of SIMULINK in Engineering.

9. Practical Examples of SIMULINK in Engineering.

Control Engineering Lab 3/101


Lab-1

Introduction to MATLAB its functions and applications.

 Matlab is a tool for doing numerical computations with matrices and vectors. It can
also display information graphically. The best way to learn what Matlab can do is to work
through some examples at the computer.

 Matlab program and script files always have filenames ending with ".m"; the
programming language is exceptionally straightforward since almost every data object is
assumed to be an array. Graphical output is available to supplement numerical results.

1.0 Entering the matrices and simple matrix manipulation

1.1 Matrices

To enter the matrix


1 2
3 4
and store it in a variable a, do this:
>> a = [ 1 2; 3 4 ]
To redisplay the matrix, just type its name:
>> a

Once you know how to enter and display matrices, it is easy to compute with them. First we
will square the matrix a :

>> a * a

Wasn't that easy? Now we'll try something a little harder. First we define a matrix b:

>> b = [ 1 2; 0 1 ]
Then we compute the product ab:
>> a*b

Finally, we compute the product in the other order:

>> b*a

Control Engineering Lab 4/101


Notice that the two products are different: matrix multiplication is non commutative.

Of course, we can also add matrices:

Control Engineering Lab 5/101


>> a + b

Now let's store the result of this addition so that we can use it later:

>> s = a + b
Matrices can sometimes be inverted:
>> inv(s)

To check that this is correct, we compute the product of s and its inverse:

>> s * inv(s)

The result is the unit, or identity matrix. We can also write the computation as

>> s/s

We can also write

>> s\s
which is the same as
>> inv(s) * s

To see that these operations, left and right division, are really different, we do the following:

>> a/b

>> a\b

Not all matrices can be inverted, or used as the denominator in matrix division:

>> c = [ 1 1; 1 1 ]
>> inv(c);

A matrix can be inverted if and only if its determinant is nonzero:

>> det(a)
>> det(c)
A transpose of a matrix
>> a’

1.2 Building Matrices


Control Engineering Lab 6/101
Matlab has many types of matrices which are built into the system. A 7 by 7 matrix with
random entries is produced by typing

rand(7)

You can generate random matrices of other sizes and get help on the rand command within
matlab:

rand(2,5)

help rand

Another special matrix, called a Hilbert matrix, is a standard example in numerical linear
algebra.

hilb(5)

help hilb

A 5 by 5 magic square is given by the next command:

magic(5)

help magic
A magic square is a square matrix which has equal sums along all its rows and columns.
We'll use matrix multiplication to check this property a bit later.

Some of the standard matrices from linear algebra are easily produced:

eye(6)

zeros(4,7)

ones(5)

You can also build matrices of your own with any entries that you may want

1.3 Getting Workspace information

Control Engineering Lab 7/101


At any time you want to know the active variables you can use who:

who

To get the complete information we will write

Whos
>> whos
Name Size Bytes Class

A 3x3 72 double array


a 1x1 8 double array
x 3x1 24 double array

To clear the screen:

Clc

To clear the memory:

Clear

Clear (variables)

Colon Notation:
Matlab offers some powerful methods for creating arrays and for taking them apart.
x=-2:1

length(x)

-2:.5:1

-2:.2:1

a=magic(5)

a(2,3)

Now we will use the colon notation to select a column of a.

Control Engineering Lab 8/101


a(2,:)

a(:,3)

a(2:4,:)

a(:,3:5)

a(2:4,3:5)

a(1:2:5,:)

You can put a vector into a row or column position within a.

a(:,[1 2 5])

a([2 5],[2 4 5])

1.4 Complex Numbers and Matrices:

Z=3 +4i or z=3 +4j

There are at least two convenient ways to enter complex matrices.

A=[1 2;3 4] + i*[5 6;7 8]

And

A=[1=5*i 2+6*i;3+7*i 4+8*I]

1.5 Miscellaneous commands:


You may have discovered by now that MATLAB is case sensitive, that is "a" is not the same
as "A." If this proves to be an annoyance, the command

casesen

will toggle the case sensitivity off and on.

Control Engineering Lab 9/101


The MATLAB display only shows 5 digits in the default mode. The fact is that MATLAB
always keeps and computes in a double precision 16 decimal places and rounds the display to
4 digits. The command

format long

will switch to display all 16 digits and

format short

will return to the shorter display. It is also possible to toggle back and forth in the scientific
notation display with the commands

format short e

and

format long e

It is not always necessary for MATLAB to display the results of a command to the screen. If
you do not want the matrix A displayed, put a semicolon after it, A;. When MATLAB is ready
to proceed, the prompt >> will appear. Try this on a matrix right now.

Sometimes you will have spent much time creating matrices in the course of your MATLAB
session and you would like to use these same matrices in your next session. You can save these
values in a file by typing

save filename

This creates a file

filename.mat

Control Engineering Lab 10/10


1
1.6 SOLVING SIMULTANEOUS LINEAR EQUATIONS
One of the most common applications of matrix algebra
occursin the solution of linear simultaneous equations. Consider
a set of n equations for which the unknowns are x1, x2, .......
xn.

a11x1 + a12x2 + a13x3 + ............... a1nxn = b1

a21x1 + a22x2 + a23x3 + ............... a2nxn = b2

a31x1 + a32x2 + a33x3 + ............... a3nxn = b3


. . . . .
. . . . .
. . . . .
. . . . .
an1x1 + an2x2 + an3x3 + ............... annxn = bn

The matrix format for these equations is

[a][x] = [b]
where
a11 a12 a13 ..... a1n x1 b1

a21 a22 a23 ..... a2n x2 b2

[a] = a31 a32 a33 .... a3n [x] = x3 [b] = b3


. . . . . .
. . . . . .
. . . . . .
. . . . . .
an1 an2 an3 .... ann xn bn

Note that only when the equations are linear in the unknown
xi's is the matrix formulation possible.

The classical matrix solution to this equation is based on


the definition of the inverse of a matrix. The inverse of a
matrix is that matrix which when multiplied by the original
matrix, results in the identity matrix. Then

a-1 a = I

where a-1 denotes the 'inverse of matrix a' and I denotes the
identity matrix of the same order as matrix 'a'. If 'a' is a
known coefficient matrix and if 'b' is a column vector of known
terms, the problem is one of finding the n vales of x1, x2, ....

Control Engineering Lab 11/10


1
xn that satisfy these simultaneous equations. Pre-multiplying
both sides of the equation by the inverse of 'a' gives

[a-1][a][x] = [a-1][b]
or
[x] = [a-1][b]

Thus if we find the inverse of the coefficient matrix, the


product of the inverse times the matrix of non-homogeneous
terms, b, yields the unknown matrix, x. To observe the simple
property of the inverse, define the 4x4 matrix, C

C = [1 -4 3 2; 3 1 -2 1; 2 1 1 -1; 2 -1 3 1]

calculate the inverse using the 'matlab' command, inv().

C_inverse = inv(C)

and note that

C_inverse * C = [1 0 0 0;0 1 0 0;0 0 1 0;0 0 0 1]

where the right hand side is the 4x4 identity matrix.

We leave to a study of linear algebra, the method and steps


required to calculate the inverse of a matrix. Suffice it to
say here that for systems of equations numbering in the hundreds
or thousands, which often occur in complex engineering problems,
the calculation of the matrix inverse is a time consuming
operation even for modern computers.

As an example of solving a system of equations using the


matrix inverse, consider the following system of three
equations.

x1 - 4x2 + 3x3 = -7

3x1 + x2 - 2x3 = 14

2x1 + x2 + x3 = 5

Using 'matlab', define the two matrices for [a] and [b].

a = [ 1 -4 3; 3 1 -2; 2 1 1];
b = [ -7; 14; 5];

Find the solution vector, x, by

Control Engineering Lab 12/10


1
x = inv(a)*b
giving

x = [ 3
1
-2 ]

1.7 LEFT and RIGHT Matrex 'DIVISION' In MATLAB

In contrast to matrix inversion, the preferred methods of


solution for large-scale systems of simultaneous equations are
methods of back substitution whereby the equations can be
rearranged so that first xn is solved, then xn-1 and so on until
finally x1 is obtained in order. Thus in back substitution we
never solve the equations simultaneously, rather we solve them
sequentially. For example, the above set of equations can be
rearranged through appropriate combination into the below
equations. (You should carry out this algebra to ensure you
understand the steps matlab takes in solving with back
substitution. In the general case, the steps or algorithm is
much more complex than that required for 3 equations.)

x1 - 4x2 + 3x3 = -7

13x2 - 11x3 = 35

(34/13)x3 = (68/13)

In this format, we see from the third equation the solution for
x3= 2 and knowing this, the second equation yields x2 = 1, and
knowing both x3 and x2, the first equation gives x1 = 1. This
is an application of back substitution, whereby each unknown is
obtained by simple sequential solution to a single equation.
Methods of back substitution are employed by 'matlab' when we
invoke the 'right division' and 'left division' commands.

\ left division
/ right division

Understand that matrices cannot be divided. The operation is


not defined. The syntax of 'right division' and 'left division'
simply invoke back substitution methods for obtaining a solution
vector from a system of simultaneous equations. Whether 'right
division' (/) or 'left division' (\) is appropriate depend on
how the matrix equation is posed.

Left Division. If the matrix equation is

Control Engineering Lab 13/10


1
[a][x] = [b]

then we have a nxn matrix [a] pre-multiplying a nx1 matrix


[x], resulting in a nx1 matrix [b]. The solution for x is
obtained by using the left division operation.

[x] = [a]\[b]

If the matrix equation is cast in this format, the use of


right division to obtain the solution vector x will result in
an error message.

Returning to 'matlab', recall we have defined the


matrices [a] and [b] in the format of the matrix equation
appropriate for left division.

a = [ 1 -4 3; 3 1 -2; 2 1 1];
b = [ -7; 14; 5];

Now enter the command


x1 = a\b

and obtain the result

x1 = [ 3
1
-2 ]

which i s the same result found earlier for x when solving by


matrix inversion.

Right Division. The matrix format in which right division is


employed is less common but no less successful in solving the
problem of simultaneous equations. Right Division is invoked
when the equations are written in the form

[x][A] = [B]

Note that in this form [x] and [B] are row vectors rather than
column vectors as above. This form represent a 1xn matrix (x)
pre- multiplying a nxn matrix (A), resulting an a 1xn matrix
(B). Again, recalling the set of equations,

x1 - 4x2 + 3x3 = -7

Control Engineering Lab 14/10


1
3x1 + x2 - 2x3 = 14

2x1 + x2 + x3 = 5

These equations can be written in matrix format

[x][A] =[B]
if

x = [x1 x2 x3] B = [ -7 14 5]

and
1 3 2
[A] = -4 1 1
3 -2 1

Note that [A] is equal to the transpose of [a].

A = a'
Having so defined A and B, the solution for x can be obtained
by

right division.

x = B/A

results in

x = [ 3
1
-2 ]

1.8 Exercise:

1. Find the solution to

r + s + t + w = 4

2r - s + w = 2

3r + s - t - w = 2

r - 2s - 3t + w = -3

using the matrix inverse and left and right division.

2. Find the solution to

Control Engineering Lab 15/10


1
2x1 + x2 - 4x3 + 6x4 + 3x5 - 2x6 = 16

-x1 + 2x2 + 3x3 + 5x4 - 2x5 = -7

x1 - 2x2 - 5x3 + 3x4 + 2x5 + x6 = 1

4x1 + 3x2 - 2x3 + 2x4 + x6 = -1

3x1 + x2 - x3 + 4x4 + 3x5 + 6x6 = -11

5x1 + 2x2 - 2x3 + 3x4 + x5 + x6 = 5

using the matrix inverse and left and right division.

Rubric 1
Marks CLO1 – Level C2 mapped to PLO 5 (Software Usage)

02 Does not know how to use MATLAB to program and analyse data.
Major help is required in handling MATLAB.
06 Uses MATLAB to program and analyse data with minor error help.

10 Uses MATLAB to program and analyse data effectively and


confidently.

Control Engineering Lab 16/10


1
Lab-2

Introduction to MATLAB its functions and applications


Plotting, Curve Fitting (Part-II)

2.0 Plotting:

The simplest graphs to create are plots of points in the cartesian plane. For example:

>> x = [1;2;3;4;5];
>> y = [0;.25;3;1.5;2];
>> plot(x,y)
The resulting graph is displayed in Figure

Figure 2.1: A simple Matlab graph

Notice that, by default, Matlab connects the points with straight line segments. An alternative
is the following ():

>> plot(x,y,'o')

Control Engineering Lab 17/10


1
Figure 2.2: Another simple Matlab graph

All Matlab variables must have numerical values:

>> x = -10:.1:10;

The basic plot command:

>> plot(sin(x))

Figure 2.3: Graph of Sine

Note that the horizontal axis is marked according to the index, not
the value of x. Fix this as follows:

Control Engineering Lab 18/10


1
>> plot( x, sin(x) )

Figure 2.4: Another Sine curve

This is the same thing as plotting "parametric curves."

We can plot the "inverse relationship" (for example, the squaring function and +/- square
root) easily:

>> plot( x, x.^2 ) >> plot( x.^2, x )

Control Engineering Lab 19/10


1
or a spiral in two or in three dimensions:

>> t = 0:.1:10; plot( t .* >> plot3( t .* cos(t), t .*


cos(t), t .* sin(t) ) sin(t), t )

Plot several curves simultaneously with plot(x1, y1, x2,


y2, ...):

>> plot( x, cos(x), x, 1 - x.^2./2, x, 1 -


x.^2./2 + x.^4./24 )

Control Engineering Lab 20/10


1
Figure 2.5:

2.1 Putting several graphs in one window


The subplot command creates several plots in a single window. To be precise,
subplot(m,n,i) creates mn plots, arranged in an array with m rows and n columns. It also
sets the next plot command to go to the ith coordinate system (counting across the rows). Here
is an example

>> t = (0:.1:2*pi)';
>> subplot(2,2,1)
>> plot(t,sin(t))
>> subplot(2,2,2)
>> plot(t,cos(t))
>> subplot(2,2,3)
>> plot(t,exp(t))
>> subplot(2,2,4)
>> plot(t,1./(1+t.^2))

Control Engineering Lab 21/10


1
2.2 How to plot in DIFFERENT COLORS

If you have hard time seeing some of the plots that you do in
matlab on the color workstations, you should probably change
the colors.

To find out how to do that, you can type at the matlab prompt:

help plot

In short, color can be specified inside the plot command. You


can type:

plot(x,y,'w')

to plot a white line. You can also use other colors -- they
are all listed in the plot help information.

2.3 Some more about plotting


Here are other ways to graph multiple curves, using matrices (plotted by
columns) and using "hold."

Control Engineering Lab 22/10


1
Figure 2.6:

Functions of two variables may be plotted, as well, but some "setup" is required!

>> [x y] = meshgrid(-3:.1:3, -3:.1:3);


>> z = x.^2 - y.^2;

Here are two options for plotting the surface. Look at the help page for details.

Control Engineering Lab 23/10


1
Figure 2.7:

2.4 3D Plots:
In order to create a graph of a surface in 3-space (or a contour plot of a surface), it is necessary
to evaluate the function on a regular rectangular grid. This can be done using the meshgrid
command. First, create 1D vectors describing the grids in the x- and y-directions:

>> x = (0:2*pi/20:2*pi)';
>> y = (0:4*pi/40:4*pi)';

Next, ``spread'' these grids into two dimensions using meshgrid:

>> [X,Y] = meshgrid(x,y);


>> whos
Name Size Bytes Class

X 41x21 6888 double array


Y 41x21 6888 double array
x 21x1 168 double array
y 41x1 328 double array

Grand total is 1784 elements using 14272 bytes


The effect of meshgrid is to create a vector X with the x-grid along each row, and a vector Y
with the y-grid along each column. Then, using vectorized functions and/or operators, it is easy
to evaluate a function z = f(x,y) of two variables on the rectangular grid:
>> z = cos(X).*cos(2*Y);

Having created the matrix containing the samples of the function, the surface can be graphed
using either the mesh or the surf commands :

>> mesh(x,y,z)
>> surf(x,y,z)

Control Engineering Lab 24/10


1
Figure 2.8: Using the mesh command

Figure 2.9: Using the surf command

(The difference is that surf shades the surface, while mesh does not.) In addition, a contour
plot can be created :

>> contour(x,y,z)

Control Engineering Lab 25/10


1
2.5 Some More about Plotting and Graphs
plot(x,y) creates a Cartesian plot of the vectors x & y

plot(y) creates a plot of y vs. the numerical values of the


elements in the y-vector.

semilogx(x,y) plots log(x) vs y

semilogy(x,y) plots x vs log(y)

loglog(x,y) plots log(x) vs log(y)

grid creates a grid on the graphics plot

title('text') places a title at top of graphics plot

xlabel('text') writes 'text' beneath the x-axis of a plot

ylabel('text') writes 'text' beside the y-axis of a plot

text(x,y,'text') writes 'text' at the location (x,y)

text(x,y,'text','sc') writes 'text' at point x,y assuming


lower left corner is (0,0) and upper right corner is
(1,1).

Control Engineering Lab 26/10


1
polar(theta,r) creates a polar plot of the vectors r &
theta where theta is in radians.

bar(x) creates a bar graph of the vector x. (Note also the


command stairs(x).)

bar(x,y) creates a bar-graph of the elements of the vector


y, locating the bars according to the vector
elements of 'x'. (Note also the command
stairs(x,y).)

Polar plots:
angle = 0:.1*pi:3*pi;
radius = exp(angle/20);
polar(angle,radius),...
title('An Example Polar Plot'),...
grid

Bar graph:

bar(x,y) and bar(y)


stair (x,y) and stair(y)

Multiple plots:
x1=0:.05*pi:pi;
y1=sin(x1);
plot(x1,y1)
hold
y2=cos(x1);
plot(x1,y2)

You can create multiple graphs by using multiple arguments.


In addition to the vectors x,y created earlier, create the
vectors a,b and plot both vector sets simultaneously as follows.
a = 1 : .1 : 3;
b = 10*exp(-a);
plot(x,y,a,b)

Multiple plots can be accomplished also by using matrices rather


than simple vectors in the argument. If the arguments of the
'plot' command are matrices, the COLUMNS of y are plotted on
the ordinate against the COLUMNS of x on the abscissa.

2.6 How to Plot a File of data points

Control Engineering Lab 27/10


1
Matlab is actually quite useful even for things as simple as
plotting a file of data points. First you'll need a file with
all the proper values. Let's say you have a file with all your
data, arranged like this:

x1 y1
x2 y2
x3 y3
.. ..
xn yn

Let's additionally say that the name of the file is "test.dat".


To load the data into matlab you would type the following at
the matlab prompt:

load test.dat

Then "test" becomes a matrix where the first column is X and


the second column is Y. To plot this, you can type:

plot( test(:,1), test(:,2) )

Where "test(:,1)" means "the entire first column of matrix


test".

Exercise: Put the following data by creating a fine in the note


pad and store it with test1.dat in the matlab work space.

x = 2,4 10,25,16,13,14,18
y = -1,2,4,7,6,12,13,-16

Now load this file and plot y vs x.

2.7 EQUATION FITTING


Many occasions arise when we have a set of (x,y) pairs and
we desire to find an equation or function that "fits" these
data. The procedure we follow can be generally classified in
one of two categories, interpolating functions or least squares
functions.

The least-squares function is one that obtains the best


fit, where the meaning here of "best" is based on minimizing
the sum of the squares of the differences between the function
and the data pairs. Clearly the idea of "least squares" is to
achieve some sort of average or mean value function whose

Control Engineering Lab 28/10


1
graphical curve does not typically pass through any of the (x,y)
data pairs. It is
appropriate for experimental data in which every data pair is
obtained under conditions of uncertainty and for which any
collected data, as a consequence of experimental error, may be
greater or less than the true value.

2.8 INTERPOLATING POLYNOMIAL

The interpolating function is one that satisfies every data


point exactly. When viewed in a graphical plot, the
interpolating function passes through each data point. If for
convenience we select the polynomial form as the function, a
polynomial of degree 'n' can be found for a set of 'n+1' (x,y)
data pairs. The general form of the polynomial can be written

y = a0 + a1x + a2x2 + a3x3 + ....... + anxn

To evaluate the interpolating polynomial of degree 'n' for any


data set, we must evaluate 'n+1' coefficients, a0, a1, a2, a3,
.....an. Given the 'n+1' (x,y) data pairs, we can form 'n+1'
equations

y1 = a0 + a1x1 + a2x12 + a3x13 + ...... + anx1n


y2 = a0 + a1x2 + a2x22 + a3x23 + ...... + anx2n
y3 = a0 + a1x3 + a2x32 + a3x33 + ...... + anx3n
. . . . . .
. . . . . .
. . . . . .

yn+1 = a0 + a1xn+1 + a2xn+12 + a3xn+13 + ... + anxn+1n

This is a solvable set of 'n+1' equations with 'n+1' unknowns.


The unknowns are the coefficients a0, a1,......an. If there
exists only two or three equations, the solution procedure for
the unknown coefficients can conveniently follow Cramer's Rule.
In general, however, it is common to rely on matrix algebra to
manipulate these equations into a format for which n operations
of back substitution will obtain the unknown coefficients. Here
we will simply rely on the methods of right (or left) division
in 'matlab' to obtain the unknown coefficients, leaving the
details of the numerical method for back substitution for later
discussion.

Note that the set of equations can be conveniently


expressed by the matrix equation

[y] = [X][a]

Control Engineering Lab 29/10


1
where

y1 1 x1 x12.....x1n+1 a1

y2 1 x2 x22.....x2n+1 a2
[y] = [X] = [a] =
y3 1 x3 x32.....x3n+1 a3
. . . . . .
. . . . . .
. . . . . .
yn+1 1 xn+1 xn+12... xn+1n+1 an+1

Note that the right side of the matrix equation must be the
product of a 'n+1' x 'n+1' square matrix times a 'n+1' x 1
column matrix! The solution using Gauss elimination calls for
left division in 'matlab' or

[a] = [X]\[y]

Using this method, we can find the coefficients for a n-


degree polynomial that passes exactly through 'n+1' data
points.

If we have a large data set, each data pair including some


experimental error, the n-degree polynomial is NOT A GOOD
CHOICE. Polynomials of degree larger than five or six often
have terribly unrealistic behavior BETWEEN the data points even
though the polynomial curve passes through every data point !
As an example, consider these data.

x y

2 4
3 3
4 5
5 4
6 7
7 5
8 7
9 10
10 9

There are 9 data points in this set. It is clear that as x


increases, so also does y increase; however, it appears to be
doing so in a nonlinear way. Let's see what the data looks
like. In 'matlab', create two vectors for these data.

x9 = [2:1:10];

Control Engineering Lab 30/10


1
y9 = [ 4 3 5 4 7 5 7 10 9 ];

To observe these data plotted as points, execute

plot(x9,y9,'o')

Because we have nine data pairs, it is possible to construct


an eighth-degree interpolating polynomial.

y = a0 + a1x + a2x2 + a3x3 + ....... + a8x8

To find the unknown coefficients, define the column vector y

y = y9'

and the matrix X

X =
[ones(1,9);x9;x9.^2;x9.^3;x9.^4;x9.^5;x9.^6;x9.^7;x9.^8]'

Note that X is defined using the transpose, the ones() function


and the array operator ' .^ '. With X and y so defined, they
satisfy the equation

[X][a] = [y]

Solve for the coefficients, matrix a in the aboveequation, by


entering the command

a = X\y

which results in

a = [ 1.0e+003*
3.8140
-6.6204
4.7831
-1.8859
.4457
- .0649
.0057
- .0003
.0000 ]

Note that the ninth coefficient a(8) appears to be zero.


Actually, it is finite, it only appears to be zero because

Control Engineering Lab 31/10


1
'matlab' is printing only 4 significant figures to the left of
the decimal point. To observe the coefficients with more
significant figures, enter the commands

format long a

and the format is changed to one with 15 significant digits.


Clearly a(8) is not zero, it is a small number because it is
multiplying a number, x, raised to the eight power.

Now that we have the coefficients, let's generate a sufficient


number of points to create a smooth curve. For x, form a vector
over the range 2 <= x <= 10 in increments of 0.1.

x = [ 2:.1:10 ];

For y, calculate the value of the eighth degree polynomial for


each x.

y =a(1)+ a(2).*x + a(3).*x.^2 + a(4).*x.^3 +


a(5).*x.^4...
+ a(6).*x.^5 + a(7).*x.^6 + a(8).*x.^7 + a(9).*x.^8;

Now plot (x,y) and the data points (x9,y9).

plot(x,y,x9,y9,'o')

The polynomial results appear to pass exactly through every data


point, but clearly the polynomial is useless for representing
our impression of the data at any other point within the range
of x! This is a common behavior for high-order interpolating
polynomials. For this reason, one should never attempt to use
high order interpolating polynomials to represent experimental
data.

Marks CLO1 – Level C2 mapped to PLO 5 (Software Usage)

02 Does not know how to use MATLAB to program and analyse data.
Major help is required in handling MATLAB.
06 Uses MATLAB to program and analyse data with minor error help.

10 Uses MATLAB to program and analyse data effectively and


confidently.

Control Engineering Lab 32/10


1
Lab-3

Introduction to MATLAB its functions and applications.


Programming, Solution of ODE, Polynomial roots, Partial
Fractions (Part-III)

3.0 Programming in Matlab:

The capabilities of Matlab can be extended through programs


written in its own programming language. It provides the
standard constructs, such as loops and conditionals; these
constructs can be used interactively to reduce the tedium of
repetitive tasks, or collected in programs stored in ``m-files''
(nothing more than a text file with extension ``.m''). I will
first discuss the programming mechanisms and then explain how
to write programs

3.1 Conditionals and loops


Matlab has a standard if-elseif-else conditional; for example:

>> t = rand(1);
>> if t > 0.75
s = 0;
elseif t < 0.25
s = 1;
else
s = 1-2*(t-0.25);
end
>> s
s =
0
>> t
t =
0.7622
The logical operators in Matlab are <, >, <=, >=, == (logical equals), and ~= (not equal).
These are binary operators which return the values 0 and 1 (for scalar arguments):
>> 5>3
ans =
1
>> 5<3
ans =
0
>> 5==3
ans =
0

Control Engineering Lab 33/10


1
Thus the general form of the if statement is

if expr1
statements
elseif expr2
statements
.
.
.
else
statements
end

The first block of statements following a nonzero expr executes.

Matlab provides two types of loops, a for-loop (comparable to a Fortran do-loop or a C for-
loop) and a while-loop. A for-loop repeats the statements in the loop as the loop index takes
on the values in a given row vector:

>> for i=[1,2,3,4]


disp(i^2)
end
1
4
9
16
(Note the use of the built-in function disp, which simply displays its argument.) The loop,
like an if-block, must be terminated by end. This loop would more commonly be written as

>> for i=1:4


disp(i^2)
end
1
4
9
16
(recall that 1:4 is the same as [1,2,3,4]).

The while-loop repeats as long as the given expr is true (nonzero):

>> x=1;
>> while 1+x > 1
x = x/2;
end
>> x
x =
1.1102e-16

Control Engineering Lab 34/10


1
3.3 Solution of ordinary differential Equations:

Matlab can numerically solve Ordinary Differential equations


using 2 methods.

ODE23 uses 2nd and 3rd order Runge-Kutta formulas


and
ODE45 uses 4th and 5th order Runge-Kutta formulas

What you first need to do is to break your ODE into a system


of 1st orde equations. For instance,

.. . 2
X + AX + K X = 0 <= Damped harmonic oscillator

can be written as,


.
Y1 = Y2
. 2
Y2 = - A Y2 - K Y1
.
(Let Y1=X and Y2=X)

Now, you need to write a matlab function that takes Y1, Y2,
and time as arguments and returns Y1 and Y2. To do this,
create a file using matlab editor or your own favorite editor
that contains the following:

function [Ydot] = myode(t,Y)

% Note: Y(1) => Y1 and Y(2) => Y2


% t is for time..

if your equations do not contain t, you still have


% to put a "t" in the function declaration above.

A = 1.3333; % Whatever values you want to choose


K= 2.132;

Ydot(1) = Y(2);
Ydot(2) = -A*Y(2)-K^2*Y(1);

Ydot = Ydot'; % This makes Ydot into a column vector

Control Engineering Lab 35/10


1
Call this file "myode.m" and save it in a place where matlab
knows to look for it (either the directory from which you
started matlab or your own directory for example
/mit/username/matlab/).

Now, the moment we have been waiting for: let's solve this
ODE. At the matlab prompt, type:

>> [T,Y]=ode45('myode',[0 10],[0 1]);

Note:

'myode': Name of the function you wrote above


[0 10] : Integrate from t=0 to t=10 (seconds)
[0 1] : Initial conditions for your system.. [1 0]
corresponds to system where,

X(t=0) = 1
.
X(t=0) = 0

Which you can think of as a pendulum that has been pulled


back and is being let go at t=0. (in this case the pendulum is
damped by the A term)

To see the results, type:

>> plot(T,Y)
or,
>> plot(T,Y(:,1),'-',T,Y(:,2),'--');

Here, the solid line corresponds to X (displacement) and the


dashed line
.
to X (speed).

Your coefficients to your equations do not have to be constant.


They can depend on time. For instance if your oscillator is
damped and driven:

.. . 2
X + AX + K X = B cos(wt)

Your m-file will look something like this:

Control Engineering Lab 36/10


1
function [Ydot] = myode2(t,Y)

% Note: Y(1) => Y1 and Y(2) => Y2


% t is for time.. if your equations do not contain t, you
still have
% to put a "t" in the function declaration above.

A = 1.3333; % Whatever values you want to choose


K= 2.132;
B=.2;
w=2;

Ydot(1) = Y(2);
Ydot(2) = -A*Y(2)-K^2*Y(1)+B*cos(w*t);

Ydot = Ydot'; % This makes Ydot into a column vector

You might try experimenting with the coefficients to see what


happens.

>> [T,Y]=ode45('myode2',[0 10], [0 0]); plot(T,Y);

----------------------------------------------------------------

3.4 Some more examples on Ordinary Differential Equation

Make the program and solve the following equation. Submit the program as well as the result
print out.

.. .
y(t ) 3 y(t )  2 y(t )  f (t )
.
y(0)  1 y(0)  0
f (t )  1 t  0

Control Engineering Lab 37/10


1
3.5 Roots of a polynomial:

Roots of a polynomial can be found

B=roots(a)

Where a is coefficient matrix of the polynomial.

3.6 Multiplication of two factors:

(x2+2x-1)(x+1)

It can be multiplied

A=[1 2 –1] and b=[1 1]

C=conv(a,b) where c is the result.\

[q,r]= deconv(c,a) this gives back the factors

3.7 Partial Fractions:


[R,P,K] = RESIDUE(B,A) finds the residues, poles and direct term of a partial fraction
expansion of the ratio of two polynomials B(s)/A(s).

[B,A] = RESIDUE(R,P,K), with 3 input arguments and 2 output arguments, converts the
partial fraction expansion back to the polynomials with coefficients in B and A.

Rubric 1
Marks CLO1 – Level C2 mapped to PLO 5 (Software Usage)

02 Does not know how to use MATLAB to program and analyse data.
Major help is required in handling MATLAB.
06 Uses MATLAB to program and analyse data with minor error help.

10 Uses MATLAB to program and analyse data effectively and


confidently.

Control Engineering Lab 38/10


1
Lab-4

Introduction to some MATLAB’s Control functions

4.0 MATLAB Matrix Lab

4.1 Typical uses:

Math and computation


Algorithm development
Modeling and simulation
Data analysis, exploration and visualization
Scientific and Engineering graphics
Application development + GUI development

4.2 Tool Boxes

Communications Toolbox
Signal processing Toolbox
Filter design Toolbox
Control systems Toolbox
Optimization Toolbox
Image Processing Toolbox
Symbolic Toolbox
Financial Toolbox
Mathematics etc.

4.3 MATLAB Development environment

Command Prompt
Entering Variables
Controlling Input and output
Case sensitivity
Suppressing output

4.4 Finding roots of a transfer function and plotting its poles and zeros

Given a transfer function :

T(s) = s3+3s2+5 / (s+2)(s2+2s+9)

Writing polynomial :

Control Engineering Lab 39/10


1
num = [1 3 5]; den1 = [1 2] ; den2 = [1 2 9]
Multiplying denominator terms:

den = conv(den1,den2);

Printing a transfer function :

printsys(num,den)

Finding roots of a polynomial:

den_r = roots(den)

Combining roots to form polynomial :

den = poly(den_r);

Finding value of a polynomial at s = -x;

val_den = polyval(den,s);

Plotting poles and zeros:

pzmap(num,den)

4.5 Block Diagram Models

4.5.1 Series connection :

series()

X(s) G1(s) G2(s) Y(s) X(s) G1(s)G2(s) Y(s)

4.5.2 Parallel connection:

parallel()

G1(s)
+
Y(s)
X(s) G1(s)+-
X(s) Y(s)
 G2(s)

G2(s)
Control Engineering Lab 40/10
1
4.5.3 Closed loop transfer function calculation:

cloop()

X(s) + Y(s) G(s) /


G(s) X(s) Y(s)
1 +- G(s)


4.5.4 Feed back calculation

feedback()

X(s) + Y(s) G(s) /


G(s) X(s) 1 +- Y(s)
H(s)G(s)


H(s)

4.5.5 Minimizing a transfer function: removing common poles and zeros:


minreal()

4.6 MATLAB code in a “m” file to show all above operations

%
% ME 224 Control Systems
% Author : Liaquat Ali Khan
% Date : xx-xx-xxx
% Lab No. 1
% Class : BEMTS-VI A&B
% File name : blk_reduction_ex.m
% Description : The function implements a transfer function and demo for
% following functions:
% reducing blocks in series: series()
% reducing blocks in parallel: parallel()
% calculating closed loop gain: cloop()
% calculating feedback: feedback()
%

% Defining two functions Gs1 and Gs2


Control Engineering Lab 41/10
1
num1=[1 2];den1=[1 5 6];
num2=[1 4]; den2=[5 3 4];
printsys(num1,den1)
printsys(num2,den2)
Gs1 = tf(num1,den1);
Gs2 = tf(num2,den2);

% series()
sys = series(Gs1,Gs2)
pause

% parallel()
sys = parallel(Gs1,Gs2)
pause

sys = parallel(Gs1,-Gs2)
pause

% cloop()
% obsolete now, use feedback with H(S) = 1
sys = feedback(Gs1,1,+1)
pause

sys = feedback(Gs1,1,-1)
pause

% feedback
sys = feedback(Gs1,Gs2,+1)
pause

sys = feedback(Gs1,Gs2,-1)
pause
%
% End
%

4.7 MATLAB code in a “m” file to show minreal() operations

%
% ME 224 Control Systems
% Author : Liaquat Ali Khan
% Date : xx-xx-xxx
% Lab No. 1
% Class : BEMTS-VI A&B
% File name : min_real_ex.m
% Description : The function implements a transfer function and demo for
% following functions:
% minimizing a transfer function using minreal()
Control Engineering Lab 42/10
1
%
% Defining a T(s)
num = [1 -1 0]
den = [1 0 0 -1]

printsys(num,den)
pause

sys=tf(num,den);

min_sys = minreal(sys)
pause

%
% End
%

4.8 Exercises

You have to submit the solution of every exercise in group containing the following.

1- Theoretical solution (using Mason’s Gain and some other technique.)


2- MATLAB code and compare the two results (Graph printout should be attached.

Exercise-1:

Consider the feedback system depicted in Fig-4.1.


(a) Compute the closed-loop transfer function using the series and cloop functions, and
display the result with the printsys function,
(b) Obtain the closed-loop system unit step response with the step function, and verify
that final value of the output is 2/5.

Fig-4.1: A negative feedback control system

Control Engineering Lab 43/10


1
Exercise-2:
  
Consider the differential equation y 2 y y  u where y(t)  y(t)  0 and u(t) is a unit step.
Determine the solution y(t) analytically and verify with MATLAB by co-plotting the analytic
solution and the step response obtained with the step function.

Exercise-3:

Consider the block diagram in Fig-4.2.


(a) Use MATLAB to reduce the block diagram in Fig. 4.2 and compute the closed-
loop transfer function.
(b) Generate a pole-zero map of the closed-loop transfer function in graphical from
using the pzmap function.
(c) Determine explicitly the poles and zeros of the closed-loop transfer function using
the roots function, and correlate the results with the pole-zero map in pat (b).

Fig-4.2: A multiple-loop feedback control system block diagram.

Marks CLO2 – Level P1 mapped to PLO 5 (Software Usage)

Control Engineering Lab 44/10


1
02 Is not able to write the code in MATLAB using control functions and
interpret it. Major help is required in writing the program.
06 Can write and interpret MATLAB codes using control functions with
minor error help.
10 Can write and interpret MATLAB codes using control functions
effectively and confidently.

Control Engineering Lab 45/10


1
Lab-5

Introduction to some MATLAB’s Control functions

Analysis to the response (Transient response) of the system


5.0 Finding its settling time
System settling is a time in which most of the transient response of the system
die-out, and system reaches to its steady state value.
The system with lower settling time is a fast (better) system.

5.1 Finding the steady state value

Steady state value of the system is that value which is the desired response of
the system, This is also called system d.c. gain. Manually it can be found by
just putting s=0 in the transfer function or t=∞.

5.2 Closed-loop speed tachometer control system

Td(s)
Amplifier -
R(s) + Ea(s) + Km/ Tm(s) TL(s) 1/
w(s)
Ra + Js+b
- -

Kb

Tachometer
Vt(s)

Fig-5.1 Closed-loop speed tachometer control system


Where,
R(S) is the input voltage
w(S) is the output angular movement of motor
Td(S) is the external disturbance signal

5.2.1 Requirement:

Analyze under external Disturbance Closed loop with feedback is better:

5.2.1 Parameters to analyze:

Analyze the settling time Ts.

Control Engineering Lab 46/10


1
5.2.1.1 Case-I Consider the closed loop system without Tachometer feedback

Td(s)

-
+ Km/ Tm(s) TL(s) 1/
Va(s) w(s)
Ra + Js+b
-

Fig-5.2 Open-loop speed control system without Tachometer

Ra Km J b Kb Ka Kt
1 10 2 0.5 0.1 54 1

The resulting system reduced to the following taking step Td(s).


1
T (s) 
2s  1.5

Fig-5.3 Open-Loop system Disturbance Step Response

The approximate steady state value of w(7) = -0.66 rad/s at t = 7 sec

Control Engineering Lab 47/10


1
5.2.1.2 Case-II Consider the closed loop system with Tachometer feedback

Td(s)
Amplifier
Ea(s) -
+ Km/ Tm(s) TL(s) 1/
w(s)
Ra + Js+b
-

Tachometer
Vt(s)

Fig-5.4 Closed-loop speed tachometer control system.

The resulting transfer function is

1
T (s) 
2s  541.5

Fig-5.5 Closed-loop Disturbance Step Response

Control Engineering Lab 48/10


1
The approximate steady state value of w(0.02) = -0.02 rad/s at t = 0.02 sec.

Fig-5.6 Open-loop and Close-loop Disturbance Step Responses of the system

5.2.2 Result: Adding negative feedback, increases the Disturbance Rejection property of
the system, since steady state achieved Quickly with very little change in output
w(s).

5.2.3 MATLAB Code for the Open-loop without tachometer feedback of the above
example.

%
% ME 224 Control Systems
% Author : Liaquat Ali Khan
% Date : xxxxxxdx
% Lab No. 5
% Class : BEMTS VI (A & B)
% File name : opentach.m
% Description : The function implements the speed tachometer example.
%
%
% Define Tachometer control system parameters
Ra = 1;
Km = 10;
J = 2;
b = 0.5;
Kb = 0.1;
Ka = 54;

Control Engineering Lab 49/10


1
Kt = 1;
% Define G(s)= 1 / Js+b
num1 = [1];
den1 = [J b];
% Define H(s) = Km*Kb/Ra
num2 = [Km*Kb/Ra];
den2 = [1];
% Find the T(S)= w(s) / Td(s)
[num,den] = feedback(num1,den1,num2,den2);
% Change the sign of T(s) since Td(s) is negative
num = -num
% print the final T(S)
printsys(num,den);
% Compute response to step disturbance
[step_resp,x,t] = step(num,den);
% plot step response
figure
plot(t,step_resp);
title('Open-loop Disturbance Step Response');
xlabel('time[sec]');
ylabel('speed');
grid;
% Find steady-state error, last value of output
Final_val = step_resp(length(t))
%
% End Function
%

5.2.4 MATLAB Code for the Open-loop/Close-loop with/ without tachometer feedback of
the above example.
%
% ME 224 Control Systems
% Author : Liaquat Ali Khan
% Date xxxxxx
% Lab No. 5
% Class : BEMTS VI (A & B)
% File name : open_close_tach.m
% Description : The function implements the speed tachometer example.
%
%
% Define Tachometer control system parameters
Ra = 1;
Km = 10;
J = 2;
b = 0.5;
Kb = 0.1;
Ka = 54;
Kt = 1;
Control Engineering Lab 50/10
1
% Define G(s)= 1 / Js+b
num1 = [1];
den1 = [J b];
% Define H(s) = Km*Kb/Ra
numo = [Km*Kb/Ra];
deno = [1];
% Find the T(S)= w(s) / Td(s)
[numop,denop] = feedback(num1,den1,numo,deno);
% Change the sign of T(s) since Td(s) is negative
numop = -numop
% print the final T(S)
printsys(numop,denop);
% Compute response to step disturbance
[step_resp_op,x_op,t_op] = step(numop,denop);
%
% Define G1(s) = Ka*Kt
num2 = [Ka*Kt];
den2 = [1];
% Define G2(s) = Kb
num3 = [Kb];
den3 = [1];
% Define G3(s) = Km/Ra
num4 = [Km / Ra];
den4 = [1];
% Combine G1(s) and G2(s) in parallel
[numa,dena] = parallel(num2,den2,num3,den3);
% Combine the above and G3(s) in series
[numb,denb] = series(numa,dena,num4,den4);
% Combine the above and G(S) in feedback
[numcl,dencl] = feedback(num1,den1,numb,denb);
% Change the sign of T(s) since Td(s) is negative
numcl = -numcl
% print the final T(S)
printsys(numcl,dencl);
% Compute response to step disturbance
[step_resp_cl,x_cl,t_cl] = step(numcl,dencl);
%
figure
subplot(211)
plot(t_op,step_resp_op);
title('Open-loop Disturbance Step Response');
ylabel('speed');
grid;

subplot(212)
plot(t_cl,step_resp_cl);
title('Close-loop Disturbance Step Response');
xlabel('time[sec]');
Control Engineering Lab 51/10
1
ylabel('speed');
grid;

5.3 Designing a System

Choosing parameter values (choose value of K ) such that:


System settles in less time
Analyze for K = 20 , 100

Given a closed-loop system with two inputs R(s) and D(s)


Y(s) = T(S) R(S) + Td(s) D(S)
The system is as follows.

D(s)

E(s) +
+
R(s) K+11s 1/s(s+1) w(s)
+
-

Fig: 5.7 A block diagram model of a boring machine control system.

1
Y(s)  K 11s R(s)  D(s)
s2 12s  K s2 12s  K
5.3.1 Case-I Without Disturbance the closed loop system

E(s)
+
R(s) K+11s 1/s(s+1) w(s)
-

Fig-5.8 Closed-loop system without Disturbance

5.3.1.1 Result:
Under no disturbance System with K=20 has more settling time but low overshoot

Control Engineering Lab 52/10


1
5.3.2 Case-II Under Disturbance the system is:

D(s)

+
K+11s 1/s(s+1) w(s)
+

Fig-5.9 Closed-loop system with Disturbance

5.3.2.1 Result:
Under disturbance System with K=100 shows better performance If our
requirement is disturbance rejection then K =100 Is better choice

5.3.3 MATLAB Code for the close-loop with K=20, and K=100

%
% ME 224 Control Systems
% Author : Liaquat Ali Khan
% Date xxxxxxxxx
% Lab No. 5
% Class : BEMTS (VI and A & B)
% File name : english1.m
% Description : The function implements the English channel boring
%
%
% response to a uit step input R(s)=1/s for k = 20 and k = 100
%
numg = [1];
deng = [1 1 0];
K1 = 100;
K2 = 20;
num1 = [11 K1];
num2 = [11 K2];
den = [0 1];
%
[na,da] = series(num1,den,numg,deng);
[nb,db] = series(num2,den,numg,deng);
%
[numa,dena] = cloop(na,da);
Control Engineering Lab 53/10
1
[numb,denb] = cloop(nb,db);
%
t=[0:0.01:2.0];
[y1,x,t] = step(numa,dena,t);
[y2,x,t] = step(numb,denb,t);
%
figure
subplot(211)
plot(t,y1)
title('Step response for K=100')
ylabel('y(t)')
grid

subplot(212)
plot(t,y2)
title('Step response for K=20')
xlabel('time[sec]')
ylabel('y(t)')
grid
%
% End Function
%
Exercise-1

Consider the torsional mechanical system in the Fig-5.10. The torque due to the twisting of


the shaft is kθ; the damping torque due to the braking device is  bθ ; the disturbance
torque is d(t); the input torque is r(t); an the moment of inertia of the mechanical system is J.
The transfer function of the torsional mechanical system is shown below.

G(s)  1
s 2  (b / J )s  k / J
Suppose the desired angle θd = 0°, k = 5 , and J = 1.

Control Engineering Lab 54/10


1
Fig-5.10 A torsional mechanical system

Do the following:

(a) Draw the control canonical form of the Block diagram and the transfer function, and
also confirm the transfer function by taking transfer function using Mason’s Gain
Formula.
(b) Determine the open-loop response θ(t) of the system for a unit step disturbance d(t)
using MATLAB (set r(t)=0) . Also confirm the result by finding the analytical result.
(c) With the controller gain Ko = 50, determine the closed-loop response, θ(t), to a unit
step disturbance, d(t), using MATLAB.
(d) Co-plot the open-loop versus the closed-loop response to the disturbance input.
(e) Discuss your results and make an argument for using closed-loop feedback control to
improve the disturbance rejection properties.
(f) Write the state-space equation, from the block diagram, and confirm the transfer
function, manually and then by using MATLAB.

The function used in MATLAB for the transfer function is:

Tffss= ss (A, B, C, D)
Where, A, B, C and D are the metrics from the state space equation.

Exercise-2:

The control of the roll angel of an airplane is achieved by sing the toque developem by
the ailerons, as shown in Fig 5.11(a) and (b). A linear model of the roll control system
for a small experimental aircraft is shown in Fig 5.11(c), where q(t) is the flow of fluid
into a hydraulic cylinder and

1
G(s) 
s2  4s  9
The goal is to maintain a small roll angle θ due to disturbances. Select an appropriate
gain KK1, that will reduce the effect of the disturbance while attaining a desirable
transient response to a step disturbance, with θd(t) = 0. To require a desirable transient
response, let KK1<35. Analyze completely in MATLAB by making an “m-file”.

Control Engineering Lab 55/10


1
Fig: 5.11(a,b) Control of the roll angle of an airplane.

θ(s)

Fig: 5.11 (c) Block diagram of the Roll angle of an airplane

Note: You have to submit all the calculations, m-files, and their responses output in terms of
graphs.

Marks CLO2 – Level P1 mapped to PLO 5 (Software Usage)

02 Is not able to write the code in MATLAB using control functions and
interpret it. Major help is required in writing the program.
06 Can write and interpret MATLAB codes using control functions with
minor error help.
10 Can write and interpret MATLAB codes using control functions
effectively and confidently.

Control Engineering Lab 56/10


1
Lab-6

Responses of 1st order and 2nd Order Systems

6.0 MATLAB function used in this Lab

step (num,den) : To plot the step response of the system

Impulse(num,den) : To plot the impulse response of the system.

[y,x,t]=step(num,den): To store the values of the step response function in an array.

ym=max(y): To get the maximum amplitude of a response value.

ys = dcgain(num,den) : To get the d.c. gain of the system (steady state value)

yovrsht = (ym-yt)/ys * 100; To calculate the % over shoot.

6.1 1st Order System

For the following systems find first analytically and then by using the MATLAB the
response of the systems due to Step input and Impulse input. Also calculate the
system
(i) Time constant
(ii) Settling time
(iii) System d.c. gain.
(iv) Percent over shoot (part b only)
(v) Maximum amplitude.
(vi) Peat time

Note: Make a m. file to superimpose the two.

(a)

R(s) C(s)

Fig-6.1: Open-loop first order system.

(b)
R(s) C(s)

Control Engineering Lab 57/10


1
Fig-6.2: Open-loop 2nd order system

(c) Make (a) and (b) as the unity feedback system and find the closed loop transfer
function and step response of the system. Do manually and then by doing
everything using MATLAB m.file.

π 4
TP  Ts  M PT  1  eζπ / β
ϖn ςϖ
n

%overshoot  eζπ / β x100


6.2 Step response of a second order system with varying value of damping coefficient
(ζ)

For the given generalized 2nd order system given below

G(s)  wn2
s2  2ζ wn  wn2
The step response of this 2nd order system is as follows.

1
c(t)  1  eζϖ n sin( θ )
t
nt
βϖ β
β  1  ζ 2

Plot the different responses with varying ωnt (0-14) take ωn=1 rad/s. Vary the value
of ζ from 0 to 2 with an increment of 0.1. Do everything making an m.file in
MATLAB.

6.3 Impulse response of a second order system with varying value of damping
coefficient (ζ)

Plot the impulse response of the 2nd order system given in section 5.1. The impulse
response is given below. It is actually the derivation of the step response.

Control Engineering Lab 58/10


1
ϖn
c(t)  eζϖ nt sin( βϖ nt)
β
β  1  ζ 2

Plot the different responses with varying ωnt (0-12) take ωn=1 rad/s. Vary the value
of ζ from 0 to 2 with an increment of 0.1. Do everything making an m.file in
MATLAB.

6.4 Exercise-1: The racing vehicle

The engine, body, and tires of a racing vehicle affect the acceleration and speed
attainable. The speed control of the car is represented by the model shown in the
following figure (6.3)

Fig 6.3: Racing car speed control.

(a) Calculate the steady-state error of the car to a step command in speed.
(b) Calculate overshoot of the speed to step input command, and other useful
commands mention at the beginning of the lab.

6.5 Exercise-2: Levitated train control

For year, Amtrak ahs struggled to attract passengers on its routs in the Midwest, using
technology developed decades ago. During the same time, foreign railroads were developing
new passenger rai systems that could profitably compete with air travel. Two of these systems,
the French TGV and the Japanese Shinkansen, each speeds of 160 mph. The tranrapid-06, a
U.S. experimental magnetic levitation train is shown in the following figure.

The use of magnetic levitation and electro-magnetic propulsion to provide contact less
vehicle movement makes the Transrapid-06 technology radically different from the existing

Control Engineering Lab 59/10


1
Metroliner. The underside of the TR-06 carriage (where the wheel trucks would be on a
conventional car) wraps around a guideway. Magnets on the bottom of the guideway attract
electromagnets on the “wraparound” pulling it up toward the guideway. This suspends the
vehicle about one centimeter above the guideway.

The levitation control is represented by Fig(6.4).

(a) Find the step response for K=40, and also calculate the percent over shoot.
(b) Select or analyze the value of K such that the over shoot is not more than 5%
for the step input.

Fig 6.4: Levitated train control

6.6 Exercise-3: A plant control model:

A feedback system with negative unity feedback has a plant

2(s  8)
G(s) 
s(s  4)
(a) Determine the closed-loop transfer function T(s)=Y(s)/R(s) using manually, and
using the MATLAB.

Control Engineering Lab 60/10


1
(b) Find the time response y(t) for the unit step input.
(c) Determine the over shoot of the response.
(d) Using the final-value theorem, and using the response plot find the steady-state
values of y(t)
(e) Find the system settling time manually and from the plot.

6.7 Exercise-4: Blood-sugar level control:

Effective control of insulin injections can result in better lives for diabetic persons.
Automatically controlled insulin injection by means of a pump and a sensor that
measures blood sugar can be very effective. A pump and injection system has a
feedback control as shown in Fig(6.5). Calculate the suitable gain K so that the
overshoot of the step response due to the drug injection is approximately 7%. R(s) is
the desired blood-sugar level and Y(s) is the actual blood-sugar level.

Fig 6.5: Blood-sugar level control

6.8 Exercise-5: Roll angel Control of an autopilot air-craft

The roll control autopilot of a jet fighter is shown in the Fig(6.6). The goal is to
select a suitable K so that the response to a unit step command φd(t)=1, t ≥ 0, will
provide a reponse φ(t) that is a fast response andhas an overshoot of less than 20%.

(a) Determine the closed-llop transfer function φ(s)/φd(s).


(b) Determine the roots of the characteristic equation for K = 0.7, 3 and 6.
(c) Find the over shoot of the approximated 2nd order system.
(d) Select the gain K so that the percentage overshoot is equal to 16%. What is the
resulting peak time?

Control Engineering Lab 61/10


1
Fig 6.6: Roll angle control

Marks CLO2 – Level P1 mapped to PLO 5 (Software Usage)

02 Is not able to write the code in MATLAB using control functions and
interpret it. Major help is required in writing the program.
06 Can write and interpret MATLAB codes using control functions with
minor error help.
10 Can write and interpret MATLAB codes using control functions
effectively and confidently.

Control Engineering Lab 62/10


1
Lab-7

Introduction and Some Basic Application of SIMULINK


7.1 Introduction:

Simulink is a time based software package that is included in Matlab and its main task is to
solve Ordinary Differential Equations (ODE) numerically. The need for the numerical
solution comes from the fact that there is not an analytical solution for all DE, especially for
those that are nonlinear.

The whole idea is to break the ODE into small time segments and to calculate the solution
numerically for only a small segment. The length of each segment is called “step size”. Since
the method is numerical and not analytical there will be an error in the solution. The error
depends on the specific method and on the step size (usually denoted by h).

There are various formulas that can solve these equations numerically. Simulink uses
Dormand-Prince (ODE5), fourth-order Runge-Kutta (ODE4), Bogacki-Shampine (ODE3),
improved Euler (ODE2) and Euler (ODE1). A rule of thumb states that the error in ODE5 is
proportional to h5, in ODE4 to h4 and so on. Hence the higher the method the smaller the error.

Unfortunately the high order methods (like ODE5) are very slow. To overcome this problem
variable step size solvers are used. When the system’s states change very slowly then the step
size can increase and hence the simulation is faster. On the other hand if the states change
rapidly then the step size must be sufficiently small.

The variable step size methods that Simulink uses are:


• An explicit Runge-Kutta (4,5) formula, the Dormand-Prince pair (ODE45).
• An explicit Runge-Kutta (2,3) pair of Bogacki and Shampine (ODE23).
• A variable-order Adams-Bashforth-Moulton PECE solver (ODE113).
• A variable order solver based on the numerical differentiation formulas (NDFs) (ODE15s).
• A modified Rosenbrock formula of order 2 (ODE23s).
• An implementation of the trapezoidal rule using a "free" interpolant (ODE23t).
• An implementation of TR-BDF2, an implicit Runge-Kutta formula with a first stage that is a
trapezoidal rule step and a second stage that is a backward differentiation formula of order two
(ODE23tb).

To summarize the best method is ODE5 (or ODE45), unless you have a stiff problem, and a
smaller the step size is better, within reason.

7.2 Solving ODE:

Since the key idea of Simulink is to solve ODE let us see an example of how to accomplish
that. Through that example many important features of Simulink will be revealed.

To start Simulink click on the appropriate push button from the command window:

Control Engineering Lab 63/10


1
You will see the Simulink window.

Control Engineering Lab 64/10


1
Open a new Simulink window by clicking on the New button.

7.3 Basic Elements of SIMULINK:

There are two major classes of items in Simulink: blocks and lines. Blocks are used
to generate, modify, combine, output, and display signals. Lines are used to transfer
signals from one block to another.

(i) Blocks
(ii) Lines

7.3.1 Blocks:

There are several general classes of blocks:

 Sources: Used to generate various signals


 Sinks: Used to output or display signals
 Discrete: Linear, discrete-time system elements (transfer functions, state-space
models, etc.)
 Linear: Linear, continuous-time system elements and connections (summing
junctions, gains, etc.)
 Nonlinear: Nonlinear operators (arbitrary functions, saturation, delay, etc.)
 Connections: Multiplex, Demultiplex, System Macros, etc.

Blocks have zero to several input terminals and zero to several output terminals. Unused
input terminals are indicated by a small open triangle. Unused output terminals are indicated
by a small triangular point. The block shown below has an unused input terminal on the left
and an unused output terminal on the right.

7.3.2 Lines:
Lines transmit signals in the direction indicated by the arrow. Lines must always transmit
signals from the output terminal of one block to the input terminal of another block. On
exception to this is a line can tap off of another line, splitting the signal to each of two
destination blocks, as shown below.

Control Engineering Lab 65/10


1
Lines can never inject a signal into another line; lines must be combined through the use of a
block such as a summing junction.

A signal can be either a scalar signal or a vector signal. For Single-Input, Single-Output
systems, scalar signals are generally used. For Multi-Input, Multi-Output systems, vector
signals are often used, consisting of two or more scalar signals. The lines used to transmit
scalar and vector signals are identical. The type of signal carried by a line is determined by
the blocks on either end of the line.

7.3.3 Model File:

In Simulink, a model is a collection of blocks which, in general, represents a system. In


addition, to drawing a model into a blank model window, previously saved model files can
be loaded either from the File menu or from the MATLAB command prompt.

7.3.4 Example:

The simple model consists of three blocks: Step, Transfer Fcn, and Scope. The Step is a
source block from which a step input signal originates. This signal is transfered through the
line in the direction indicated by the arrow to the Transfer Function linear block. The
Transfer Function modifies its input signal and outputs a new signal on a line to the Scope.
The Scope is a sink block used to display a signal much like an oscilloscope.

There are many more types of blocks available in Simulink, some of which will be discussed
later. Right now, we will examine just the three we have used in the simple model.

Control Engineering Lab 66/10


1
7.3.5 Modifying Blocks

A block can be modified by double-clicking on it. For example, if you double-click on the
"Transfer Fcn" block in the simple model, you will see the following dialog box.

This dialog box contains fields for the numerator and the denominator of the block's transfer
function. By entering a vector containing the coefficients of the desired numerator or
denominator polynomial, the desired transfer function can be entered. For example, to
change the denominator to s^2+2s+1, enter the following into the denominator field:
[1 2 1]
and hit the close button, the model window will change to the following,

which reflects the change in the denominator of the transfer function.

The "step" block can also be double-clicked, bringing up the following dialog box.

Control Engineering Lab 67/10


1
The default parameters in this dialog box generate a step function occurring at time=1 sec,
from an initial level of zero to a level of 1. (in other words, a unit step at t=1). Each of these
parameters can be changed. Close this dialog before continuing.

The most complicated of these three blocks is the "Scope" block. Double clicking on this
brings

7.4 Building Systems:

In this section, you will learn how to build systems in Simulink using the building blocks in
Simulink's Block Libraries. You will build the following system.

First you will gather all the necessary blocks from the block libraries. Then you will modify
the blocks so they correspond to the blocks in the desired model. Finally, you will connect the
blocks with lines to form the complete system. After this, you will simulate the complete
system to verify that it works.

Control Engineering Lab 68/10


1
7.4.1 Gathering Blocks:
Follow the steps below to collect the necessary blocks:

 Create a new model (New from the File menu or Ctrl-N). You will get a blank model
window.

 Double-click on the Sources icon in the main Simulink window.





This opens the Sources window which contains the Sources Block Library. Sources are
used to generate signals.

Control Engineering Lab 69/10


1
 Drag the Step block from the sources window into the left side of your model
window.


Control Engineering Lab 70/10


1
 Double-click on the Linear icon in the main Simulink window to open the Linear
Block Library window.
 Drag the Sum, Gain, and two instances of the Transfer Fcn (drag it two times) into your
model window arranged approximately as shown below. The exact alignment is not
important since it can be changed later. Just try to get the correct relative positions.
Notice that the second Transfer Function block has a 1 after its name. Since no two
blocks may have the same name, Simulink automatically appends numbers following
the names of blocks to differentiate between them.

 Double-click on the Sinks icon in the main Simulink window to open the Sinks
window.
 Drag the Scope block into the right side of your model window.



7.4.2 Modify Blocks:

Follow these steps to properly modify the blocks in your model.

 Double-click your Sum block. Since you will want the second input to be subtracted,
enter +- into the list of signs field. Close the dialog box.

Control Engineering Lab 71/10


1
 Double-click your Gain block. Change the gain to 2.5 and close the dialog box.
 Double-click the leftmost Transfer Function block. Change the numerator to [1 2] and
the denominator to [1 0]. Close the dialog box.
 Double-click the rightmost Transfer Function block. Leave the numerator [1], but
change the denominator to [1 2 4]. Close the dialog box. Your model should appear
as:

 Change the name of the first Transfer Function block by clicking on the words
"Transfer Fcn". A box and an editing cursor will appear on the block's name as shown
below. Use the keyboard (the mouse is also useful) to delete the existing name and
type in the new name, "PI Controller". Click anywhere outside the name box to finish
editing.

 Similarly, change the name of the second Transfer Function block from "Transfer
Fcn1" to "Plant". Now, all the blocks are entered properly. Your model should appear
as:

Control Engineering Lab 72/10


1
7.4.2 Connecting Blocks with Lines:
Now that the blocks are properly laid out, you will now connect them together. Follow these
steps.

 Drag the mouse from the output terminal of the Step block to the upper (positive) input
of the Sum block. Let go of the mouse button only when the mouse is right on the input
terminal. Do not worry about the path you follow while dragging, the line will route
itself. You should see the following.

The resulting line should have a filled arrowhead. If the arrowhead is open, as shown
below, it means it is not connected to anything.

Control Engineering Lab 73/10


1
You can continue the partial line you just drew by treating the open arrowhead as an output
terminal and drawing just as before. Alternatively, if you want to redraw the line, or if the
line connected to the wrong terminal, you should delete the line and redraw it. To delete a
line (or any other object), simply click on it to select it, and hit the delete key.

 Draw a line connecting the Sum block output to the Gain input. Also draw a line from
the Gain to the PI Controller, a line from the PI Controller to the Plant, and a line
from the Plant to the Scope. You should now have the following.

 The line remaining to be drawn is the feedback signal connecting the output of the
Plant to the negative input of the Sum block. This line is different in two ways. First,
since this line loops around and does not simply follow the shortest (right-angled)
route so it needs to be drawn in several stages. Second, there is no output terminal to
start from, so the line has to tap off of an existing line.

To tap off the output line, hold the Ctrl key while dragging the mouse from the
point on the existing line where you want to tap off. In this case, start just to the

Control Engineering Lab 74/10


1
right of the Plant. Drag until you get to the lower left corner of the desired feedback
signal line as shown below.

Now, the open arrowhead of this partial line can be treated as an output terminal.
Draw a line from it to the negative terminal of the Sum block in the usual manner.

 Now, you will align the blocks with each other for a neater appearance. Once
connected, the actual positions of the blocks does not matter, but it is easier to read if
they are aligned. To move each block, drag it with the mouse. The lines will stay
connected and re-route themselves. The middles and corners of lines can also be
dragged to different locations. Starting at the left, drag each block so that the lines
connecting them are purely horizontal. Also, adjust the spacing between blocks to leave
room for signal labels. You should have something like:

Control Engineering Lab 75/10


1
 Finally, you will place labels in your model to identify the signals. To place a label
anywhere in your model, double click at the point you want the label to be. Start by
double clicking above the line leading from the Step block. You will get a blank text
box with an editing cursor as shown below

Type an r in this box, labeling the reference signal and click outside it to end editing.
Label the error (e) signal, the control (u) signal, and the output (y) signal in the same
manner. Your final model should appear as:

Control Engineering Lab 76/10


1
 To save your model, select Save As in the File menu and type in any desired model
name.

7.5 Simulation
Now that the model is complete, you can simulate the model. Select Start from the
Simulation menu to run the simulation. Double-click on the Scope block to view its output.
Hit the autoscale button (binoculars) and you should see the following.

7.6 Taking Variables from MATLAB


In some cases, parameters, such as gain, may be calculated in MATLAB to be used in a Simulink
model. If this is the case, it is not necessary to enter the result of the M ATLAB calculation
directly into Simulink. For example, suppose we calculated the gain in MATLAB in the variable
K. Emulate this by entering the following command at the MATLAB command prompt.
K=2.5
This variable can now be used in the Simulink Gain block. In your Simulink model, double-
click on the Gain block and enter the following in the Gain field. K

Control Engineering Lab 77/10


1
Close this dialog box. Notice now that the Gain block in the Simulink model shows the
variable K rather than a number.

Now, you can re-run the simulation and view the output on the Scope. The result should be
the same as before.

Control Engineering Lab 78/10


1
Now, if any calculations are done in MATLAB to change any of the variable used in the
Simulink model, the simulation will use the new values the next time it is run. To try this, in
MATLAB, change the gain, K, by entering the following at the command prompt.
K=5
Start the Simulink simulation again, bring up the Scope window, and hit the autoscale button.
You will see the following output which reflects the new, higher gain.

Besides variable, signals, and even entire systems can be exchanged between MATLAB and
Simulink.

Requirement From Students:

1- Students should read this lab handout carefully, and understand the basics of
SIMULINK.
2- They should perform the complete exercise, simulate it and save the model also.
3- They should attach the SIMULINK model and as well as the simulation response
of their practice. Results will be similar to those given in the handout.

Marks CLO2 – Level P1 mapped to PLO 5 (Software Usage)

02 Is not able to write the code in MATLAB using control functions and
interpret it. Major help is required in writing the program.
06 Can write and interpret MATLAB codes using control functions with
minor error help.
10 Can write and interpret MATLAB codes using control functions
effectively and confidently.

Control Engineering Lab 79/10


1
Control Engineering Lab 80/10
1
Lab-8

Practical Examples of SIMULINK in Engineering

7.1 Example-1: A Coil and its Magnetic Field


d
Consider the coil shown in the next figure-7.1 The voltage supply is equal to: u(t)  i(t)  
dt
Assuming that the inductance of the coil is constant the above equation is:
di(t)
u(t)  i(t)R  L . This is a linear 1st order ODE. What is the response of the current to a
dt
sudden change of the voltage, assuming zero initial conditions? To answer this we must solve
the above ODE. There are various ways to solve it (Laplace...). Here we will try to solve it
numerically with Simulink

Figure: 7.1 Coil with AC Current with magnetic field.

di(t) 1
Step 1: First of all we must isolate the highest derivative:  (u(t)  i(t)R)
dt L
Step 2: We will use as many integrators as the order of the DE that we want to solve:
The integrator block is in:

Control Engineering Lab 81/10


1
Just click and drag the block to the model:

Control Engineering Lab 82/10


1
Step 3: Beginning at the input of the integrator we construct what we need, hence here we
1
must create the factor (u(t)  i(t)R) which is equal to Di(t). First put a gain
L
of 1/L.

To set the value of the gain block double click on it and then change its value:

Control Engineering Lab 83/10


1
Step 4: Now the term [u(t)-I(t)R] must be constructed, we will need a summation point and
another gain:

Control Engineering Lab 84/10


1
Step 5: Now we must add an input signal to simulate the voltage change and something to
see the response of the current. For the voltage change we chose to use a step input of
amplitude 1 and for the output we can use a scope:

Step 6: To run the simulation we must give values to L, R. In the workspace we type:
R=0.01; L=0.01.
Step 7: To see the solution we must run the simulation and then double click on the Scope:

Control Engineering Lab 85/10


1
7.2 Example-2: Mass Spring System
The second example is a classical mass-spring system:

_
By applying Newton’s second law:  F  ma or F (t)  Kx(t)  Bu(t)  ma(t) where F is
the external force applied on the mass (m), K is the spring constant, a is the acceleration of
the mass, u is the speed of the mass, x is the distance that is covered and B is the friction
dx(t) d 2x(t)
factor. F (t)  K Bm . The question here is what is going to be the
dt dt 2
behaviour of the mass due to a sudden force change, assuming again zero initial conditions.
To solve we will follow the previous steps:

d 2x(t)  1 dx(t)
First isolate the highest derivative: 2
 (F (t)  k  B)
dt m dt

Control Engineering Lab 86/10


1
Secondly place as many integrators as the order of the DE:

Beginning from the end construct everything that you need:

Control Engineering Lab 87/10


1
7.3 Example 3: Simple Pendulum

The pendulum shown has the following nonlinear DE:

Its Simulink block is:

Control Engineering Lab 88/10


1
To find its response we must double click on the last integrator whose output is the angle θ
and set the initial conditions to 1.

7.4 Exercise:

Requirement From Students:

4- Students should read this lab handout carefully, and perform everything using
SIMULINK.
5- They should perform the complete exercise, simulate it and save the model also.
6- They should attach the SIMULINK model and as well as the simulation response
of their practice. Results will be similar to those given in the handout.

Control Engineering Lab 89/10


1
Marks CLO2 – Level C6 mapped to PLO 4 (Investigation)

02 Is not able to analyse the system. Major help is required in writing the
program and analysing the results.
06 Can analyse and interpret the response of system with minor error help.

10 Can analyse and interpret system response effectively and confidently.

Control Engineering Lab 90/10


1
Lab-9

Practical Examples of SIMULINK in Engineering

9.1 Example: Second Order System Example


Simulation of the impulse and step response of a second-order continuous-time transfer
function:

1. Start the Matlab engine and type simulink3 at the Matlab command prompt. This
will start the Simulink3 library.

Control Engineering Lab 91/10


1
Control Engineering Lab 92/10
1
Control Engineering Lab 93/10
1
Control Engineering Lab 94/10
1
Control Engineering Lab 95/10
1
Control Engineering Lab 96/10
1
Control Engineering Lab 97/10
1
Control Engineering Lab 98/10
1
9.1.1 Requirement From Students:

7- Students should read this lab handout carefully, and perform everything using
SIMULINK.
8- They should perform the complete exercise, simulate it and save the model also.
9- They should attach the SIMULINK model and as well as the simulation response
of their practice. Results will be similar to those given in the handout.

9.2 Description of tracked vehicle turning control:


The design of a turning control for a tracked vehicle involves the selection of two parameters.
In Figure9.1, the system shown in panel
(a) has the model shown in panel
(b) The parameters a and K affect the performance of the system, including its stability.

Control Engineering Lab 99/10


1
Fig-9.1: Tracked vehicle control system. (a) Turning control system for
a two-track vehicle. (b) Linear system model.

9.2.1 Routh’s criterion for internal stability


a. Determine the closed-loop characteristic polynomial for the model shown in Fig.
1(b).
b. Generate Routh’s array for this characteristic polynomial.
c. Determine under what conditions (i.e., values of a and K) the closed-loop system is
internally stable.
d. In MATLAB, plot the curve of a versus K (for K > 0) that divides the regions of
stability and instability, and indicate on the plot which is the stable region.

9.2.2 Steady state error to a ramp reference


For a unity-gain closed-loop feedback system with open-loop transfer function Gc(s)G(s),
reference r(t), output y(t) and error e(t) = r(t) − y(t), the steady-state error is:

a. Derive the steady-state error ess for a ramp reference r(t) = At, t > 0.
b. Determine under what conditions (i.e., values of a and K) the steady-state error is less
than or equal to 22% of the ramp slope A.

9.2.3 Simulation of the model in Simulink


Create a Simulink model of the control system with a ramp .

Control Engineering Lab 100/1


01
a. Using the same values for a and K that you used in Section 3a above, plot the ramp
reference r(t) and the model output y(t) versus t and confirm that the system is stable and
that the steady-state error is less than or equal to 22% of the ramp slope A—try this for a
couple of different values of A.
b. Using the same values for a and K that you used in Section 3d above, plot the ramp
reference r(t) and the model output y(t) versus t and confirm that the system is indeed
unstable with these parameters.

Marks CLO2 – Level C6 mapped to PLO 4 (Investigation)

02 Is not able to analyse the system. Major help is required in writing the
program and analysing the results.
06 Can analyse and interpret the response of system with minor error help.

10 Can analyse and interpret system response effectively and confidently.

Control Engineering Lab 101/1


01

You might also like