Вы находитесь на странице: 1из 197

Simulink Basics Tutorial

Starting Simulink
Model Files
Basic Elements
Running Simulations
Building Systems

Simulink is a graphical extension to MATLAB for modeling and simulation of systems. In


Simulink, systems are drawn on screen as block diagrams. Many elements of block
diagrams are available, such as transfer functions, summing junctions, etc., as well as
virtual input and output devices such as function generators and oscilloscopes. Simulink
is integrated with MATLAB and data can be easily transfered between the programs. In
these tutorials, we will apply Simulink to the examples from the MATLAB tutorials to
model the systems, build controllers, and simulate the systems. Simulink is supported on
Unix, Macintosh, and Windows environments; and is included in the student version of
MATLAB for personal computers. For more information on Simulink, contact the
MathWorks.

The idea behind these tutorials is that you can view them in one window while
running Simulink in another window. System model files can be downloaded
from the tutorials and opened in Simulink. You will modify and extend these
system while learning to use Simulink for system modeling, control, and
simulation. Do not confuse the windows, icons, and menus in the tutorials for
your actual Simulink windows. Most images in these tutorials are not live they simply display what you should see in your own Simulink windows. All
Simulink operations should be done in your Simulink windows.

Starting Simulink
Simulink is started from the MATLAB command prompt by entering the following
command:
simulink

Alternatively, you can hit the New Simulink Model button at the top of the MATLAB
command window as shown below:

When it starts, Simulink brings up two windows. The first is the main Simulink window,
which appears as:

The second window is a blank, untitled, model window. This is the window into which a
new model can be drawn.

Model Files
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. As an
example, download the following model file by clicking on the following link and saving
the file in the directory you are running MATLAB from.
simple.mdl

Open this file in Simulink by entering the following command in the MATLAB command
window. (Alternatively, you can load this file using the Open option in the File menu in
Simulink, or by hitting Ctrl+O in Simulink.)
simple

The following model window should appear.

A new model can be created by selecting New from the File menu in any Simulink
window (or by hitting Ctrl+N).

Basic Elements
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.

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.

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 (click the figure to download the model file called
split.mdl).

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.

Simple Example

The simple model (from the model file section) 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.

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.

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 up a blank oscilloscope screen.

When a simulation is performed, the signal which feeds into the scope will be displayed
in this window. Detailed operation of the scope will not be covered in this tutorial. The
only function we will use is the autoscale button, which appears as a pair of binoculars in
the upper portion of the window.

Running Simulations
To run a simulation, we will work with the following model file:
simple2.mdl

Download and open this file in Simulink following the previous instructions for this file.
You should see the following model window.

Before running a simulation of this system, first open the scope window by doubleclicking on the scope block. Then, to start the simulation, either select Start from the
Simulation menu (as shown below) or hit Ctrl-T in the model window.

The simulation should run very quickly and the scope window will appear as shown
below.

Note that the simulation output (shown in yellow) is at a very low level relative to the
axes of the scope. To fix this, hit the autoscale button (binoculars), which will rescale the
axes as shown below.

Note that the step response does not begin until t=1. This can be changed by doubleclicking on the "step" block. Now, we will change the parameters of the system and
simulate the system again. Double-click on the "Transfer Fcn" block in the model
window and change the denominator to
[1 20 400]

Re-run the simulation (hit Ctrl-T) and you should see what appears as a flat line in the
scope window. Hit the autoscale button, and you should see the following in the scope
window.

Notice that the autoscale button only changes the vertical axis. Since the new transfer
function has a very fast response, it it compressed into a very narrow part of the scope
window. This is not really a problem with the scope, but with the simulation itself.
Simulink simulated the system for a full ten seconds even though the system had reached
steady state shortly after one second.
To correct this, you need to change the parameters of the simulation itself. In the model
window, select Parameters from the Simulation menu. You will see the following dialog
box.

There are many simulation parameter options; we will only be concerned with the start
and stop times, which tell Simulink over what time period to perform the simulation.

Change Start time from 0.0 to 0.8 (since the step doesn't occur until t=1.0. Change Stop
time from 10.0 to 2.0, which should be only shortly after the system settles. Close the
dialog box and rerun the simulation. After hitting the autoscale button, the scope window
should provide a much better display of the step response as shown below.

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.

If you would like to download the completed model, here.


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.

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. Click here for more information on block

libraries.

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

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.

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

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.

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 (rightangled) 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
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:

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:

To save your model, select Save As in the File menu and type in any desired
model name. The completed model can be found here.

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.

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 MATLAB
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

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.

Now, if any calculations are done in MATLAB to change any of the variab 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 variab, signals, and even entire systems can be exchanged between MATLAB and
Simulink. For more information, click here.

We will examine three of the ways in which Simulink can interact with MATLAB.
Block parameters can be defined from MATLAB variab.
Signals can be exchanged between Simulink and MATLAB.
Entire systems can be extracted from Simulink into MATLAB.

Block Parameters from MATLAB Variables


Often, a controller will be designed in MATLAB and verified in a Simulink model.
Normally, numerical parameters such as gains and controller transfer functions are
entered into simulink manually by entering the numbers in the block dialog boxes. Rather
than enter numbers directly, it is possible to use MATLAB variab in Simulink block dialog
boxes.
For example, bring up the Simulink model built in the Basics tutorial (or click here to
download it.)

In this case, the complete controller transfer function is:


s+2
2.5 ----s

Suppose this transfer function were generated by some computation in MATLAB. In this
case, there would most likely be three variab, the numerator polynomial, the denominator
polynomial, and the gain. Enter the following commands in MATLAB to generate these
variab.
K=2.5
num=[1 2]
den=[1 0]

These variab can now be used in the blocks in Simulink. In your simulink model, doubleclick on the Gain block. Enter the following in the Gain field.
K

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

Double-click on the PI Controller block. Enter the following into the Numerator field.
num

Enter the following into the Denominator field.


den

Close this dialog box. Notice now that the PI Controller block shows the variab num and
den (as functions of s) rather than an explicit transfer function.

You can simulate the model with the MATLAB variable parameters. 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.

Now, if any calculations are done in MATLAB to change any of the variab 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.

To download the model with MATLAB variable parameters, click here.

Exchanging Signals with MATLAB


Sometimes, we would like to use the results of a Simulink simulation in the MATLAB
command window for further calculations and plotting. Less often, we would like to
generate signals in MATLAB which we then use as inputs in a Simulink model. These
tasks are accomplished through the use of the To Workspace Sink Block and the From

Workspace Source Block. We will only transfer signals from Simulink to MATLAB. Doing
the reverse is a very similar process.
The To Workspace Sink Block saves a signal as a vector in the MATLAB Workspace.
Open the model which you used previously in this tutorial or click here to download the
model. Be sure that the variab K (=5), num (=[1 2]), and den (=[1 0]) are defined in
MATLAB.

Suppose
we would like to use both the output signal and the control signal for calculations in
MATLAB. We will save these two variab as well as a time signal from our Simulink
model. First, you need to generate a time signal. Open the Sources window by doubleclicking the Sources icon in the main Simulink window. Drag the Clock block from the
Sources window to the lower portion of your Simulink model.

Now, open the Sinks window and drag three instances of the To Workspace block to your
Simulink window, arranged approximately as shown below.

Before connecting these blocks to the rest of your system, first you will name the variab
to which they output. The lower To Workspace block will output the time signal to the
MATLAB variable t. Double-click on this block and enter the following in the Variable
Name field.
t

Close the dialog box. Notice that the lower To Workspace block shows a t.

The To
Workspace block near the Plant block will output the control signal to the MATLAB
variable u. Edit this block to output to the variable u. The last To Workspace block will
output the output signal to the MATLAB variable y. Edit this block to output to the
variable y. Also, for better clarity, change the labels (by clicking on the exiting labels "To
Workspace") of these blocks to "time", "control", and "output".

Now, you will connect these blocks to the rest of your system. Draw a line from the
Clock block to the time (t) block. Tap a line off of the control signal (the line between the
PI Controller block and the Plant block) and connect it to the control (u) block.
Remember, to tap off an existing line, hold the Ctrl key while drawing the line. Tap a line
off the output signal line (the line which enters the Scope block) and connect it to the
output (y) block. Your system should appear as follows.

Start the simulation (Start from the Simulation menu). You can still view the output in
the Scope window (remember autoscale).

You can now examine the outputted variab in the MATLAB window. Plot u and y vs. t by
entering the following command.
plot(t,u,t,y);

Note that it is important to plot each of these variab against the time vector generated by
Simulink, since the time between elements in the signal vectors u and y may be unequal,
particularly near a discontinuity such as the step input. Your plot of u (blue) and y (green)
should appear as follows.

To download the model with outputs to MATLAB variab, click here.

Extracting Models From Simulink into MATLAB


Sometimes, we may build a complicated model in simulink and would like to derive
either a transfer function or a state space model of the entire system. In order to do this,
you first need to define the input and output signals of the model to be extracted. These
virtual signals can be any signal in a model, for example, if we can generate an input-tooutput transfer function or a disturbance-to-error transfer function. These signals are
defined using the In and Out Connection Blocks.
Once the input/output model is defined, the Simulink model must be saved to a .mdl file.
This file is then referenced in the MATLAB command window by the linmod command.
To demonstrate this, bring up your model from the previous section of this tutorial (or
click here to download it). Be sure that the variab K (=5), num (=[1 2]), and den (=[1 0])
are defined in MATLAB.

You will be extracting a closed-loop reference-to-output model. Therefore, The virtual


input will be put in place of the step input to the system. First, delete the Step block (click
on it and hit the delete key). The previous line will remain with an an open input terminal
where it used to connect to the Step. Open the Connections window from the main
Simulink window. Drag an In Block from the Connections window to your model
window in place of the Step block you just deleted. Move the In block until the output
terminal of the In block touches the open input terminal of the left over line. The line
should attach to the In block.

The virtual output does not need to replace an existing block - the signal can be tapped
off an existing line. Drag an Out block from the Connections window and place it just
above the Scope block. Tap a line off the output signal (hold Ctrl) and connect it to the
out block.

Now, save this model under a new name. Call it mymodel.mdl. You can download a
version here.
At the MATLAB prompt, enter the following command to extract a state-space model
from your model file.
[A,B,C,D]=linmod('mymodel')

You should see the following output.


A =

-2
1
0

-9
0
-5

2
0
0

B =
5
0
5
C =
0
D =
0

This can, of course, be converted to a transfer function with the following command.
[numcl,dencl]=ss2tf(A,B,C,D)

You should get the following output.


numcl =
0
dencl =

5.0000

10.0000

1.0000

2.0000

9.0000

10.0000

To verify that the model transfered properly, you can obtain a step response of the
extracted model.
step(numcl,dencl)

You should see the following plot which is similar to the previous Simulink Scope output.

We will examine three of the ways in which Simulink can interact with MATLAB.
Block parameters can be defined from MATLAB variab.
Signals can be exchanged between Simulink and MATLAB.
Entire systems can be extracted from Simulink into MATLAB.

Block Parameters from MATLAB Variables


Often, a controller will be designed in MATLAB and verified in a Simulink model.
Normally, numerical parameters such as gains and controller transfer functions are
entered into simulink manually by entering the numbers in the block dialog boxes. Rather
than enter numbers directly, it is possible to use MATLAB variab in Simulink block dialog
boxes.
For example, bring up the Simulink model built in the Basics tutorial (or click here to
download it.)

In this case, the complete controller transfer function is:


s+2
2.5 ----s

Suppose this transfer function were generated by some computation in MATLAB. In this
case, there would most likely be three variab, the numerator polynomial, the denominator
polynomial, and the gain. Enter the following commands in MATLAB to generate these
variab.
K=2.5
num=[1 2]
den=[1 0]

These variab can now be used in the blocks in Simulink. In your simulink model, doubleclick on the Gain block. Enter the following in the Gain field.
K

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

Double-click on the PI Controller block. Enter the following into the Numerator field.
num

Enter the following into the Denominator field.


den

Close this dialog box. Notice now that the PI Controller block shows the variab num and
den (as functions of s) rather than an explicit transfer function.

You can simulate the model with the MATLAB variable parameters. 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.

Now, if any calculations are done in MATLAB to change any of the variab 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.

To download the model with MATLAB variable parameters, click here.

Exchanging Signals with MATLAB


Sometimes, we would like to use the results of a Simulink simulation in the MATLAB
command window for further calculations and plotting. Less often, we would like to
generate signals in MATLAB which we then use as inputs in a Simulink model. These
tasks are accomplished through the use of the To Workspace Sink Block and the From

Workspace Source Block. We will only transfer signals from Simulink to MATLAB. Doing
the reverse is a very similar process.
The To Workspace Sink Block saves a signal as a vector in the MATLAB Workspace.
Open the model which you used previously in this tutorial or click here to download the
model. Be sure that the variab K (=5), num (=[1 2]), and den (=[1 0]) are defined in
MATLAB.

Suppose
we would like to use both the output signal and the control signal for calculations in
MATLAB. We will save these two variab as well as a time signal from our Simulink
model. First, you need to generate a time signal. Open the Sources window by doubleclicking the Sources icon in the main Simulink window. Drag the Clock block from the
Sources window to the lower portion of your Simulink model.

Now, open the Sinks window and drag three instances of the To Workspace block to your
Simulink window, arranged approximately as shown below.

Before connecting these blocks to the rest of your system, first you will name the variab
to which they output. The lower To Workspace block will output the time signal to the
MATLAB variable t. Double-click on this block and enter the following in the Variable
Name field.
t

Close the dialog box. Notice that the lower To Workspace block shows a t.

The To
Workspace block near the Plant block will output the control signal to the MATLAB
variable u. Edit this block to output to the variable u. The last To Workspace block will
output the output signal to the MATLAB variable y. Edit this block to output to the
variable y. Also, for better clarity, change the labels (by clicking on the exiting labels "To
Workspace") of these blocks to "time", "control", and "output".

Now, you will connect these blocks to the rest of your system. Draw a line from the
Clock block to the time (t) block. Tap a line off of the control signal (the line between the
PI Controller block and the Plant block) and connect it to the control (u) block.
Remember, to tap off an existing line, hold the Ctrl key while drawing the line. Tap a line
off the output signal line (the line which enters the Scope block) and connect it to the
output (y) block. Your system should appear as follows.

Start the simulation (Start from the Simulation menu). You can still view the output in
the Scope window (remember autoscale).

You can now examine the outputted variab in the MATLAB window. Plot u and y vs. t by
entering the following command.
plot(t,u,t,y);

Note that it is important to plot each of these variab against the time vector generated by
Simulink, since the time between elements in the signal vectors u and y may be unequal,
particularly near a discontinuity such as the step input. Your plot of u (blue) and y (green)
should appear as follows.

To download the model with outputs to MATLAB variab, click here.

Extracting Models From Simulink into MATLAB


Sometimes, we may build a complicated model in simulink and would like to derive
either a transfer function or a state space model of the entire system. In order to do this,
you first need to define the input and output signals of the model to be extracted. These
virtual signals can be any signal in a model, for example, if we can generate an input-tooutput transfer function or a disturbance-to-error transfer function. These signals are
defined using the In and Out Connection Blocks.
Once the input/output model is defined, the Simulink model must be saved to a .mdl file.
This file is then referenced in the MATLAB command window by the linmod command.
To demonstrate this, bring up your model from the previous section of this tutorial (or
click here to download it). Be sure that the variab K (=5), num (=[1 2]), and den (=[1 0])
are defined in MATLAB.

You will be extracting a closed-loop reference-to-output model. Therefore, The virtual


input will be put in place of the step input to the system. First, delete the Step block (click
on it and hit the delete key). The previous line will remain with an an open input terminal
where it used to connect to the Step. Open the Connections window from the main
Simulink window. Drag an In Block from the Connections window to your model
window in place of the Step block you just deleted. Move the In block until the output
terminal of the In block touches the open input terminal of the left over line. The line
should attach to the In block.

The virtual output does not need to replace an existing block - the signal can be tapped
off an existing line. Drag an Out block from the Connections window and place it just
above the Scope block. Tap a line off the output signal (hold Ctrl) and connect it to the
out block.

Now, save this model under a new name. Call it mymodel.mdl. You can download a
version here.
At the MATLAB prompt, enter the following command to extract a state-space model
from your model file.
[A,B,C,D]=linmod('mymodel')

You should see the following output.


A =

-2
1
0

-9
0
-5

2
0
0

B =
5
0
5
C =
0
D =
0

This can, of course, be converted to a transfer function with the following command.
[numcl,dencl]=ss2tf(A,B,C,D)

You should get the following output.


numcl =
0
dencl =

5.0000

10.0000

1.0000

2.0000

9.0000

10.0000

To verify that the model transfered properly, you can obtain a step response of the
extracted model.
step(numcl,dencl)

You should see the following plot which is similar to the previous Simulink Scope output.

Simulink Examples Index


Example

Description Tutorial

Cruise Control
Motor Speed Control
Motor Position Control
Bus Suspension
Inverted Pendulum
Pitch Control
Ball and Beam

Descriptions of the MATLAB tutorial examples are available here.

Cruise Control

This is a simple example of the modeling and control of a first order system. This model
takes inertia and damping into account. Newton's laws are modeled directly in this
example, where forces are summed up to provide the acceleration of the vehicle. A simple
PI controller is implemented.

Motor Speed Control

A DC motor has second order speed dynamics when mechanical properties such as inertia
and damping as well as electrical properties such as inductance and resistance are taken
into account. Newton's law and Kirchoff's law are modeled directly by summing forces
and summing voltages to provide the motor's acceleration and armature current,
respectively. A lag compensator is implemented.

Motor Position Control

The model of the position dynamics of a DC motor is third order, because measuring
position is equivalent to integrating speed, which adds an order to the motor speed
example. In this example, however, the motor parameters are taken from an actual DC
motor used in an undergraduate controls course. This motor has very small inductance,
which effectively reduces the example to second order. This uses the same model as the
motor speed example with an additional integrator to provide position from the velocity
signal. In this example, a discrete-time model extraction and a discrete-time controller are
implemented around the continuous plant model.

Bus Suspension

This example looks at the active control of the vertical motion of a bus suspension. It
takes into account both the inertia of the bus and the inertia of the suspension/tires, as
well as springs and dampers. An actuator is added between the suspension and the bus.
Newton's law is modeled directly by summing forces acting on each of the two inertias. A
full-state feedback controller is implemented by extracting a set of states directly from
the model.

Inverted Pendulum

The inverted pendulum is a classic controls demonstration where a pole is balanced


vertically on a motorized cart. It is interesting because without control, the system is
unstable. This is a fourth order nonlinear system. This is a particularly difficult system to
model in Simulink because of the algebraic constraint. While Newton's laws are still
modeled directly, some calculations must be done in advance to derive the form of the
algebraic constraint. A PID controller is implemented using Simulink's built-in PID
block.

Pitch Control

The pitch angle of an airplane is controlled by adjusting the angle (and therefore the lift
force) of the rear elevator. The aerodynamic forces (lift and drag) as well as the airplane's
inertia are taken into account. This is a third order, nonlinear system which is linearized
about the operating point. The Simulink model is based on the State-Space model
developed in the MATLAB tutorials, and the state equations are implemented directly.
Because of this, the state vector is available for use in a full-state-feedback controller.

Ball and Beam

This is another classic controls demo. A ball is placed on a straight beam and rolls back
and forth as one end of the beam is raised and lowered by a cam. The position of the ball
is controlled by changing the angular position of the cam. This is a second order system,
since only the inertia of the ball is taken into account, and not that of the cam or the
beam. Rather than modeling forces and accelerations, the Lagrangian equations of motion
are implemented is Simulink, eliminating the need to express the algebraic constraint
explicitly as was done in the inverted pendulum example.

Simulink Modeling Tutorial


Train system
Free body diagram and Newton's law
Model Construction
Running the Model
Obtaining MATLAB Model
In Simulink, it is very straightforward to represent a physical system or a model. In
general, a dynamic system can be constructed from just basic physical laws. We will
demonstrate through an example.

Train system
In this example, we will consider a toy train consisting of an engine and a car. Assuming
that the train only travels in one direction, we want to apply control to the train so that it
has a smooth start-up and stop, along with a constant-speed ride.
The mass of the engine and the car will be represented by M1 and M2, respectively. The
two are held together by a spring, which has the stiffness coefficient of k. F represents the
force applied by the engine, and the Greek letter, mu (which will also be represented by
the letter u), represents the coefficient of rolling friction.

Free body diagram and Newton's law


The system can be represented by following Free Body Diagrams.

From Newton's law, you know that the sum of forces acting on a mass equals the mass
times its acceleration. In this case, the forces acting on M1 are the spring, the friction and
the force applied by the engine. The forces acting on M2 are the spring and the friction.
In the vertical direction, the gravitational force is canceled by the normal force applied by
the ground, so that there will be no acceleration in the vertical direction. We will begin to
construct the model simply from the expressions:
Sum(forces_on_M1)=M1*x1''
Sum(forces_on_M1)=M1*x1''

Constructing The Model


This set of system equations can now be represented graphically, without further
manipulation. First, we will construct two copies (one for each mass) of the expressions
sum_F=Ma or a=1/M*sum_F. Open a new model window, and drag two Sum blocks
(from the Linear library), one above the other. Label these Sum blocks "Sum_F1" and
"Sum_F2".

The outputs of each of these Sum blocks represents the sum of the forces acting on each
mass. Multiplying by 1/M will give us the acceleration. Drag two Gain blocks into your
model and attach each one with a line to the outputs of the Sum blocks.

These Gain blocks should contain 1/M for each of the masses. We will be taking these
variab as M1 and M2 from the MATLAB environment, so we can just enter the variab in
the Gain blocks. Double-click on the upper Gain block and enter the following into the
Gain field.
1/M1

Similarly, change the second Gain block to the following.


1/M2

Now, you will notice that the gains did not appear in the Gain blocks, and just "-K-"
shows up. This is because the blocks are two small on the screen to show 1/M2 inside the
triangle. The blocks can be resized so that the actual gain can be seen. To resize a block,
select it by clicking on it once. Small squares will appear at the corners. Drag one of
these squares to stretch the block.

When the Gain blocks are of sufficient size to display the actual gains, re-align them with

the signal line output from the Sum blocks. Also, label these two Gain blocks "a1" and
"a2".

The outputs of these gain blocks are the accelerations of each of the masses. We are
interested in both the velocities and the positions of the masses. Since velocity is the
integral of acceleration, and position is the integral of velocity, we can generate these
signals using integrator blocks. Drag two integrator blocks into your model for each of
the two accelerations. Connect them with lines in two chains as shown below. Label these
integrators "v1", "x1", "v2", and "x2" since these are the signals these integrators will
generate.

Now, drag two Scopes from the Sinks library into your model and connect them to the
outputs of these integrators. Label them "View_x1" and "View_x2".

Now we are ready to add in the forces acting on each mass. First, you need to adjust the
inputs on each Sum block to represent the proper number (we will worry about the sign
later) of forces. There are a total of 3 forces acting on M1, so change the Sum_F1 block's
dialog box entry to:
+++

There are only 2 forces acting on M2, so we can leave Sum_F1 alone for now.

The first force acting on M1 is just the input force, F. Drag a Signal Generator block from
the Sources library and connect it to the uppermost input of the Sum_F1 block. Label the
Signal Generator "F".

The next force acting on M1 is the friction force. This force is equal to:
F_friction_1=mu*g*M1*v1

To generate this force, we can tap off the velocity signal and multiply by a gain,
mu*g*M1. Drag a Gain block into your model window. Tap off the line coming from the
v1 integrator and connect it to the input of the Gain block (draw this line in several steps
if necessary). Connect the output of the Gain block to the second input of Sum_F1.
Change the gain of this gain block to the following.
mu*g*M1

Resize the Gain block to display the gain and label the gain block Friction_1.

This force, however, acts in the negative x1-direction. Therefore, it must come into the
Sum_F1 block with negative sign. Change the list of signs of Sum_F1 to
+-+

The last force acting on M1 is the spring force between masses. This is equal to:
k*(x1-x2)

First, we need to generate (x1-x2) which we can then multiply by k to generate the force.
Drag a Sum block below the rest of your model. Label it "(x1-x2)" and change its list of
signs to
-+

Since this summation comes from right to left, we need to flip the block around. Select
the bloc by single-clicking on it and select Flip from the Format menu (or hit Ctrl-F).
You should see the following.

Now, tap off the x2 signal and connect it to the negative input of the (x1-x2) Sum block.
Tap off the x1 signal and connect it to the positive input. This will cause the lines to
cross. Lines may cross, but they are only actually connected where a small block appears
(such as at a tap point).

Now, we can multiply this position difference by the spring constant to generate the
spring force. Drag a Gain block into your model to the left of the Sum blocks. Change it's
value to k and label it "spring". Connect the output of the (x1-x2) block to the input of the
spring block, and the output of the spring block to the third input of Sum_F1. Change the
third sign of Sum_F1 to negative (use +--).

Now, we can apply forces to M2. For the first force, we will use the same spring force we
just generated, except that it adds in with positive sign. Simply tap off the output of the
spring block and connect it to the first input of Sum_F2.

The last force to add in the the friction on M2. This is done in the exact same manner as
the friction on M1, tapping off v2, multiplying by a gain of mu*g*M2 and adding to
Sum_F2 with negative sign. After constructing this, you should have the following.

Now the model is complete. We simply need to supply the proper input and view the
proper output. The input of the system will be the force, F, provided by the engine. We
already have placed the function generator at the input. The output of the system will be
the velocity of the engine. Drag a Scope block from the Sinks block library into your
model. Tap a line off the output of the "v1" integrator block to view the output. Label the
scope "View_v1".

Now, the model is complete. Save your model in any file you like. You can download the
completed model here.

Running the Model


Before running the model, we need to assign numerical values to each of the variab used
in the model. For the train system, let
M1 = 1 kg
M2 = 0.5 kg
k = 1 N/sec
F= 1 N
u = 0.002 sec/m
g = 9.8 m/s^2

Create an new m-file and enter the following commands.


M1=1;
M2=0.5;
k=1;
F=1;
mu=0.002;
g=9.8;

Execute your m-file to define these values. Simulink will recognize MATLAB variab for
use in the model.
Now, we need to give an appropriate input to the engine. Double-click on the function
generator (F block). Select a square wave with frequency .001Hz and amplitude -1
(positive amplitude steps negative before stepping positive).

The last step before running the simulation is to select an appropriate simulation time. To
view one cycle of the .001Hz square wave, we should simulate for 1000 seconds. Select
Parameters from the Simulation menu and change the Stop Time field to 1000. Close
the dialog box.
Now, run the simulation and open the View_v1 scope to examine the velocity output (hit
autoscale). The input was a square wave with two steps, one positive and one negative.
Physically, this means the engine first went forward, then in reverse. The velocity output
reflects this.

Obtaining MATLAB Model


We can now extract a MATLAB model (state-space or transfer function) from out simulink
model. In order to do this, delete the View_v1 scope and put an Out Block (from the
Connections library) in its place. Also, delete the F function generator block and put an In
Block (from the Connections library) in its place. The in and out blocks define the input
and output of the system we would like to extract. For a detailed description of this

process and other ways of integrating MATLAB with Simulink, click here.

Save this model as train2.mdl or download our version here. Now, we can extract the
model into MATLAB. Enter the following command at the MATLAB command window to
extract a state-space model.
[A,B,C,D]=linmod('train2')

You should see the following output which shows a state-space model of your Simulink
model.
A =
-0.0196
0
0
1.0000

0
-0.0196
1.0000
0

1.0000
-2.0000
0
0

-1.0000
2.0000
0
0

B =
1
0
0
0
C =
1

D =
0

To obtain a transfer function model, enter the following command at the MATLAB
command prompt.
[num,den]=ss2tf(A,B,C,D)

You will see the following output representing the transfer function of the train system.

num =
0

1.0000

0.0196

2.0000

0.0000

1.0000

0.0392

3.0004

0.0588

0.0000

den =

These models are equivalent (although the states are in different order) to the model
obtained by hand in the MATLAB tutorials.

MATLAB Modeling Tutorial


Train system
Free body diagram and Newton's law
State-variable and output equations
MATLAB representation
MATLAB can be used to represent a physical system or a model. In this tutorial, you will
learn how to enter a differential equation model into MATLAB. Let's start with a review of
how to represent a physical system as a set of differential equations.

Train system
In this example, we will consider a toy train consisting of an engine and a car. Assuming
that the train only travels in one direction, we want to apply control to the train so that it
has a smooth start-up and stop, along with a constant-speed ride.
The mass of the engine and the car will be represented by M1 and M2, respectively. The
two are held together by a spring, which has the stiffness coefficient of k. F represents the
force applied by the engine, and the Greek letter, mu (which will also be represented by
the letter u), represents the coefficient of rolling friction.

Free body diagram and Newton's law


The system can be represented by following Free Body Diagrams.

From Newton's law, you know that the sum of forces acting on a mass equals the mass
times its acceleration. In this case, the forces acting on M1 are the spring, the friction and
the force applied by the engine. The forces acting on M2 are the spring and the friction.
In the vertical direction, the gravitational force is canceled by the normal force applied by
the ground, so that there will be no acceleration in the vertical direction. The equations of
motion in the horizontal direction are the following:

State-variable and output equations


This set of system equations can now be manipulated into state-variable form. The state
variab are the positions, X1 and X2, and the velocities, V1 and V2; the input is F. The
state variable equations will look like the following:

Let the output of the system be the velocity of the engine. Then the output equation will
be:

1. Transfer function
To find the transfer function of the system, we first take the Laplace transforms of the
differential equations.

The output is Y(s) = V2(s) = s X2(s). The variable X1 should be algebraically eliminated
to leave an expression for Y(s)/F(s). When finding the transfer function, zero initial
conditions must be assumed. The transfer function should look like the one shown
below.

2. State-space
Another method to solve the problem is to use the state-space form. Four matrices A, B,
C, and D characterize the system behavior, and will be used to solve the problem. The
state-space form which is found from the state-variable and the output equations is shown
below.

MATLAB representation
Now we will show you how to enter the equations derived above into an m-file for
MATLAB. Since MATLAB can not manipulate symbolic variab, let's assign numerical
values to each of the variab. Let

M1 = 1 kg
M2 = 0.5 kg
k = 1 N/m
F= 1 N

u = 0.002 sec/m
g = 9.8 m/s^2

Create an new m-file and enter the following commands.


M1=1;
M2=0.5;
k=1;
F=1;
u=0.002;
g=9.8;

Now you have one of two choices: 1) Use the transfer function, or 2) Use the state-space
form to solve the problem. If you choose to use the transfer function, add the following
commands onto the end of the m-file which you have just created.
num=[M2 M2*u*g 1];
den=[M1*M2 2*M1*M2*u*g M1*k+M1*M2*u*u*g*g+M2*k M1*k*u*g+M2*k*u*g];
train=tf(num,den)

If you choose to use the state-space form, add the following commands at the end of the
m-file, instead of num and den matrices shown above.
A=[
0
1
0
0;
-k/M1 -u*g k/M1
0;
0
0
0
1;
k/M2
0
-k/M2 -u*g];
B=[ 0;
1/M1;
0;
0];
C=[0 1 0 0];
D=[0];
train=ss(A,B,C,D)
See the MATLAB basics tutorial to

learn more about entering matrices into MATLAB.

Continue solving the problem


Once the differential equation representing the system model has been entered into
MATLAB in either transfer-function or state-space form, the open loop and closed loop
system behavior can be studied.
Most operations can be done using either the transfer function or the state-space model.
Furthermore, it is simple to transfer between the two if the other form of representation is
required. If you need to learn how to convert from one representation to the other, see the
Conversions page.

This tutorial contains seven examples which allow you to learn more about modeling.
You can link to them from below.

Example: Modeling a Cruise Control


System in Simulink
Physical setup and system equations
Building the model
Open-loop response
Extracting the Model
Implementing PI control
Closed-loop response

Physical setup and system equations


The model of the cruise control system is relatively simple. If the inertia of the wheels is
neglected, and it is assumed that friction (which is proportional to the car's speed) is what
is opposing the motion of the car, then the problem is reduced to the simple mass and
damper system shown below.

Using Newton's law, modeling equations for this system becomes:


(1)
where u is the force from the engine. For this example, let's assume that

m = 1000kg
b = 50Nsec/m
u = 500N

Building the Model


This system will be modeled by summing the forces acting on the mass and integrating
the acceleration to give the velocity. Open Simulink and open a new model window. First,
we will model the integral of acceleration

Insert an Integrator Block (from the Linear block library) and draw lines to and
from its input and output terminals.
Label the input line "vdot" and the output line "v" as shown below. To add such a
label, double click in the empty space just above the line.

Since the acceleration (dv/dt) is equal to the sum of the forces divided by mass, we will
divide the incoming signal by the mass.

Insert a Gain block (from the Linear block library) connected to the integrators
input line and draw a line leading to the input of the gain.
Edit the gain block by double-clicking on it and change its value to "1/m".
Change the label of the Gain block to "inertia" by clicking on the word "Gain"
underneath the block.

Now, we will add in the forces which are represented in Equation (1). First, we will add
in the damping force.

Attach a Sum block (from the Linear block library) to the line leading to the
inertia gain.
Change the signs of this block to "+-".
Insert a gain block below the inertia block, select it by single-clicking on it, and
select Flip from the Format menu (or type Ctrl-F) to flip it left-to-right.
Set the gain value to "b" and rename this block to "damping".
Tap a line (hold Ctrl while drawing) off the integrator's output and connect it to
the input of the damping gain block.
Draw a line from the damping gain output to the negative input of the Sum Block.

The second force acting on the mass is the control input, u. We will apply a step input.

Insert a Step block (from the Sources block library) and connect it with a line to
the positive input of the Sum Block.
To view the output velocity, insert a Scope (from the Sinks block library)
connected to the output of the integrator.

To provide a appropriate step input of 500 at t=0, double-click the Step block and
set the Step Time to "0" and the Final Value to "u".

Open-loop response
To simulate this system, first, an appropriate simulation time must be set.
Select Parameters from the Simulation menu and enter "120" in the Stop Time
field. 120 seconds is long enough to view the open-loop response.

The physical parameters must now be set. Run the following commands at the MATLAB
prompt:
m=1000;
b=50;
u=500;

Run the simulation (Ctrl-t or Start on the Simulation menu). When the simulation is
finished, double-click on the scope and hit its autoscale button. You should see the
following output.

Extracting a Linear Model into MATLAB


A linear model of the system (in state space or transfer function form) can be extracted
from a Simulink model into MATLAB. This is done through the use of In and Out
Connection blocks and the MATLAB function linmod.

Replace the Step Block and Scope Block with an In Connection Block and an Out
Connection Block, respectively (these blocks can be found in the Connections
block library). This defines the input and output of the system for the extraction
process.

Save your file as "ccmodel.mdl" (select Save As from the File menu). MATLAB will
extract the linear model from the saved model file, not from the open model window. At
the MATLAB prompt, enter the following commands:

[A,B,C,D]=linmod('ccmodel')
[num,den]=ss2tf(A,B,C,D)

You should see the following output, providing both state-space and transfer function
models of the system.
A =
-0.0500
B =
1.0000e-003
C =
1
D =
0
num =
0

0.0010

1.0000

0.0500

den =

To verify the model extraction, we will generate an open-loop step response of the
extracted transfer function in MATLAB. We will multiply the numerator by 500 to
simulate a step input of 500N. Enter the following command in MATLAB.
step(500*num,den);

You should see the following plot which is equivalent to the Scope's output.

Implementing PI Control
In the cruise control example a PI controller was designed with Kp=800 and Ki=40 to
give the desired response. We will implement this in Simulink by first containing the
open-loop system from earlier in this page in a Subsystem block.
Create a new model window.
Drag a Subsystem block from the Connections block library into your new model
window.

Double click on this block. You will see a blank window representing the contents
of the subsystem (which is currently empty).
Open your previously saved model of the Cruise Control system, ccmodel.mdl.
Select Select All from the Edit menu (or Ctrl-A), and select Copy from the Edit
menu (or Ctrl-C).

Select the blank subsystem window from your new model and select Paste from
the Edit menu (or Ctrl-V). You should see your original system in this new
subsystem window. Close this window.
You should now see input and output terminals on the Subsystem block. Name
this block "plant model".

Now, we will build a PI controller around the plant model. First, we will feed back the
plant output.

Draw a line extending from the plant output.


Insert a Sum block and assign "+-" to it's inputs.
Tap a line of the output line and draw it to the negative input of the Sum block.

The output of the Sum block will provide the error signal. From this, we will generate
proportional and integral components.

Insert an integrator after the summer and connect them with a line.
Insert and connect a gain block after the integrator to provide the integral gain.
Label this integrator Ki and assign it a value of Ki.
Insert a new Gain block and connect it with a line tapped off the output of the
Sum block.
Label this gain Kp and assign it a value of Kp.

Now we will add the proportional and integral components and apply the sum to the
plant.

Insert a summer between the Ki block and the plant model and connect the
outputs of the two gain blocks to the summer inputs.
Connect the summer output to the input of the plant.

Finally, we will apply a step input and view the output on a scope.

Attach a step block to the free input of the feedback Sum block.
Attach a Scope block to the plant output.
Double-click the Step block and set the Step Time to "0" and the Final Value to
"u". This allows the input magnitude to be changed outside of simulink.

You can download our version of the closed-loop system here.


In this example, we constructed a PI controller from fundamental blocks. As an
alternative, we could have used a Transfer Function block (from the Linear block library)
to implement this in one step, as shown below.

You can download this model here.

Closed-loop response
To simulate this system, first, an appropriate simulation time must be set. Select
Parameters from the Simulation menu and enter "10" in the Stop Time field. The design
requirements included a rise time of less than 5 sec, so we simulate for 10 sec to view the
output. The physical parameters must now be set. Run the following commands at the
MATLAB prompt:
m=1000;
b=50;
u=10;
Kp=800;
Ki=40;

Run the simulation (Ctrl-t or Start on the Simulation menu). When the simulation is
finished, double-click on the scope and hit its autoscale button. You should see the
following output.

Example: DC Motor Speed Modeling in


Simulink
Physical setup
Building the model
Open-loop response
Extracting the Model
Implementing PI control
Closed-loop response

Physical setup
A common actuator in control systems is the DC motor. It directly provides rotary motion
and, coupled with wheels or drums and cables, can provide transitional motion. The
electric circuit of the armature and the free body diagram of the rotor are shown in the
following figure:

For this example, we will assume the following values for the physical parameters.
* moment of inertia of the rotor (J) = 0.01 kg.m^2/s^2
* damping ratio of the mechanical system (b) = 0.1 Nms
* electromotive force constant (K=Ke=Kt) = 0.01 Nm/Amp
* electric resistance (R) = 1 ohm
* electric inductance (L) = 0.5 H
* input (V): Source Voltage
* output (theta): position of shaft
* The rotor and shaft are assumed to be rigid
The motor torque, T, is related to the armature current, i, by a constant factor Kt. The
back emf, e, is related to the rotational velocity by the following equations:

In SI units (which we will use), Kt (armature constant) is equal to Ke (motor constant).

Building the Model


This system will be modeled by summing the torques acting on the rotor inertia and
integrating the acceleration to give the velocity. Also, Kirchoff's laws will be applied to
the armature circuit.

Open Simulink and open a new model window.

First, we will model the integrals of the rotational acceleration and of the rate of change
of armature current.

Insert an Integrator block (from the Linear block library) and draw lines to and
from its input and output terminals.
Label the input line "d2/dt2(theta)" and the output line "d/dt(theta)" as shown
below. To add such a label, double click in the empty space just above the line.
Insert another Integrator block above the previous one and draw lines to and from
its input and output terminals.
Label the input line "d/dt(i)" and the output line "i".

Next, we will start to model both Newton's law and Kirchoff's law. These laws applied to
the motor system give the following equations:

The angular acceleration is equal to 1/J multiplied by the sum of two terms (one pos., one
neg.). Similarly, the derivative of current is equal to 1/L multiplied by the sum of three
terms (one pos., two neg.).

Insert two Gain blocks, (from the Linear block library) one attached to each of the
integrators.
Edit the gain block corresponding to angular acceleration by double-clicking it
and changing its value to "1/J".
Change the label of this Gain block to "inertia" by clicking on the word "Gain"
underneath the block.
Similarly, edit the other Gain's value to "1/L" and it's label to Inductance.
Insert two Sum blocks (from the Linear block library), one attached by a line to
each of the Gain blocks.
Edit the signs of the Sum block corresponding to rotation to "+-" since one term is
positive and one is negative.
Edit the signs of the other Sum block to "-+-" to represent the signs of the terms in
Kirchoff's equation.

Now, we will add in the torques which are represented in Newton's equation. First, we
will add in the damping torque.

Insert a gain block below the inertia block, select it by single-clicking on it, and
select Flip from the Format menu (or type Ctrl-F) to flip it left-to-right.
Set the gain value to "b" and rename this block to "damping".
Tap a line (hold Ctrl while drawing) off the rotational integrator's output and
connect it to the input of the damping gain block.
Draw a line from the damping gain output to the negative input of the rotational
Sum block.

Next, we will add in the torque from the armature.

Insert a gain block attached to the positive input of the rotational Sum block with
a line.
Edit it's value to "K" to represent the motor constant and Label it "Kt".
Continue drawing the line leading from the current integrator and connect it to the
Kt gain block.

Now, we will add in the voltage terms which are represented in Kirchoff's equation. First,
we will add in the voltage drop across the coil resistance.

Insert a gain block above the inductance block, and flip it left-to-right.
Set the gain value to "R" and rename this block to "Resistance".
Tap a line (hold Ctrl while drawing) off the current integrator's output and connect
it to the input of the resistance gain block.
Draw a line from the resistance gain output to the upper negative input of the
current equation Sum block.

Next, we will add in the back emf from the motor.


Insert a gain block attached to the other negative input of the current Sum block
with a line.
Edit it's value to "K" to represent the motor constant and Label it "Ke".
Tap a line off the rotational integrator output and connect it to the Ke gain block.

The third voltage term in the Kirchoff equation is the control input, V. We will apply a
step input.

Insert a Step block (from the Sources block library) and connect it with a line to
the positive input of the current Sum block.
To view the output speed, insert a Scope (from the Sinks block library) connected
to the output of the rotational integrator.
To provide a appropriate unit step input at t=0, double-click the Step block and set
the Step Time to "0".

You can download a model file for the complete system here.

Open-loop response
To simulate this system, first, an appropriate simulation time must be set. Select
Parameters from the Simulation menu and enter "3" in the Stop Time field. 3 seconds is
long enough to view the open-loop response. The physical parameters must now be set.
Run the following commands at the MATLAB prompt:
J=0.01;
b=0.1;
K=0.01;
R=1;
L=0.5;

Run the simulation (Ctrl-t or Start on the Simulation menu). When the simulation is
finished, double-click on the scope and hit its autoscale button. You should see the
following output.

Extracting a Linear Model into MATLAB


A linear model of the system (in state space or transfer function form) can be extracted
from a Simulink model into MATLAB. This is done through the use of In and Out
Connection blocks and the MATLAB function linmod. First, replace the Step Block and
Scope Block with an In Connection Block and an Out Connection Block, respectively
(these blocks can be found in the Connections block library). This defines the input and
output of the system for the extraction process.

Save your file as "motormod.mdl" (select Save As from the File menu). MATLAB will
extract the linear model from the saved model file, not from the open model window. At
the MATLAB prompt, enter the following commands:
[A,B,C,D]=linmod('motormodel')
[num,den]=ss2tf(A,B,C,D)

You should see the following output, providing both state-space and transfer function
models of the system.
A =
-10.0000
-0.0200

1.0000
-2.0000

B =
0
2
C =
1

D =
0
num =
0

0.0000

2.0000

den =
1.0000

12.0000

20.0200

To verify the model extraction, we will generate an open-loop step response of the
extracted transfer function in MATLAB. Enter the following command in MATLAB.
step(num,den);

You should see the following plot which is equivalent to the Scope's output.

Implementing Lag Compensator Control


In the motor speed control root locus example a Lag Compensator was designed with the
following transfer function.

To implement this in Simulink, we will contain the open-loop system from earlier in this
page in a Subsystem block.

Create a new model window in Simulink.


Drag a Subsystem block from the Connections block library into your new model
window.

Double click on this block. You will see a blank window representing the contents
of the subsystem (which is currently empty).
Open your previously saved model of the Motor Speed system, motormod.mdl.
Select Select All from the Edit menu (or Ctrl-A), and select Copy from the Edit
menu (or Ctrl-C).
Select the blank subsystem window from your new model and select Paste from
the Edit menu (or Ctrl-V). You should see your original system in this new
subsystem window.
Close this window. You should now see input and output terminals on the
Subsystem block.
Name this block "plant model".

Now, we will insert a Lag Compensator into a closed-loop around the plant model. First,
we will feed back the plant output.

Draw a line extending from the plant output.


Insert a Sum block and assign "+-" to it's inputs.
Tap a line of the output line and draw it to the negative input of the Sum block.

The output of the Sum block will provide the error signal. We will feed this into a Lag
Compensator.

Insert a Transfer Function Block after the summer and connect them with a line.
Edit this block and change the Numerator field to "[50 50]" and the Denominator
field to "[1 0.01]".
Label this block "Lag Compensator".

Finally, we will apply a step input and view the output on a scope.

Attach a step block to the free input of the feedback Sum block and attach a Scope
block to the plant output.
Double-click the Step block and set the Step Time to "0".

You can download our version of the closed-loop system here.

Closed-loop response
To simulate this system, first, an appropriate simulation time must be set. Select
Parameters from the Simulation menu and enter "3" in the Stop Time field. The design
requirements included a settling time of less than 2 sec, so we simulate for 3 sec to view
the output. The physical parameters must now be set. Run the following commands at the
MATLAB prompt:
J=0.01;
b=0.1;
K=0.01;
R=1;
L=0.5;

Run the simulation (Ctrl-t or Start on the Simulation menu). When the simulation is
finished, double-click on the scope and hit its autoscale button. You should see the
following output.

Example: DC Motor Position


Modeling in Simulink
Physical setup
Building the model
Open-loop response
Extracting a digital model
Implementing digital control
Closed-loop response

Physical setup
A common actuator in control systems is the DC motor. It directly provides rotary motion
and, coupled with wheels or drums and cables, can provide transitional motion. The
electric circuit of the armature and the free body diagram of the rotor are shown in the
following figure:

For this example, we will assume the following values for the physical parameters. These
values were derived by experiment from an actual motor in Carnegie Mellon's
undergraduate controls lab.
* moment of inertia of the rotor (J) = 3.2284E-6 kg.m^2/s^2
* damping ratio of the mechanical system (b) = 3.5077E-6 Nms
* electromotive force constant (K=Ke=Kt) = 0.0274 Nm/Amp
* electric resistance (R) = 4 ohm
* electric inductance (L) = 2.75E-6 H
* input (V): Source Voltage
* output (theta): position of shaft
* The rotor and shaft are assumed to be rigid

The motor torque, T, is related to the armature current, i, by a constant factor Kt. The
back emf, e, is related to the rotational velocity by the following equations:

In SI units (which we will use), Kt (armature constant) is equal to Ke (motor constant).

Building the Model


This system will be modeled by summing the torques acting on the rotor inertia and
integrating the acceleration to give the velocity, and integrating velocity to get position.
Also, Kirchoff's laws will be applied to the armature circuit. Open Simulink and open a
new model window. First, we will model the integrals of the rotational acceleration and
of the rate of change of armature current.

Insert an Integrator block (from the Linear block library) and draw lines to and
from its input and output terminals.
Label the input line "d2/dt2(theta)" and the output line "d/dt(theta)" as shown
below. To add such a label, double click in the empty space just above the line.
Insert another Integrator block attached to the output of the previous one and draw
a line from its output terminal.
Label the output line "theta".
Insert a third Integrator block above the first one and draw lines to and from its
input and output terminals.
Label the input line "d/dt(i)" and the output line "i".

Next, we will start to model both Newton's law and Kirchoff's law. These laws applied to
the motor system give the following equations:

The angular acceleration is equal to 1/J multiplied by the sum of two terms (one pos., one
neg.). Similarly, the derivative of current is equal to 1/L multiplied by the sum of three
terms (one pos., two neg.).

Insert two Gain blocks, (from the Linear block library) one attached to each of the
leftmost integrators.
Edit the gain block corresponding to angular acceleration by double-clicking it
and changing its value to "1/J".
Change the label of this Gain block to "inertia" by clicking on the word "Gain"
underneath the block.
Similarly, edit the other Gain's value to "1/L" and it's label to Inductance.
Insert two Sum blocks (from the Linear block library), one attached by a line to
each of the Gain blocks.
Edit the signs of the Sum block corresponding to rotation to "+-" since one term is
positive and one is negative.
Edit the signs of the other Sum block to "-+-" to represent the signs of the terms in
Kirchoff's equation.

Now, we will add in the torques which are represented in Newton's equation. First, we
will add in the damping torque.

Insert a gain block below the inertia block, select it by single-clicking on it, and
select Flip from the Format menu (or type Ctrl-F) to flip it left-to-right.
Set the gain value to "b" and rename this block to "damping".
Tap a line (hold Ctrl while drawing) off the first rotational integrator's output
(d/dt(theta)) and connect it to the input of the damping gain block.
Draw a line from the damping gain output to the negative input of the rotational
Sum block.

Next, we will add in the torque from the armature.


Insert a gain block attached to the positive input of the rotational Sum block with
a line.
Edit it's value to "K" to represent the motor constant and Label it "Kt".
Continue drawing the line leading from the current integrator and connect it to the
Kt gain block.

Now, we will add in the voltage terms which are represented in Kirchoff's equation. First,
we will add in the voltage drop across the coil resistance.

Insert a gain block above the inductance block, and flip it left-to-right.
Set the gain value to "R" and rename this block to "Resistance".
Tap a line (hold Ctrl while drawing) off the current integrator's output and connect
it to the input of the resistance gain block.
Draw a line from the resistance gain output to the upper negative input of the
current equation Sum block.

Next, we will add in the back emf from the motor.


Insert a gain block attached to the other negative input of the current Sum block
with a line.
Edit it's value to "K" to represent the motor constant and Label it "Ke".
Tap a line off the first rotational integrator's output (d/dt(theta)) and connect it to
the Ke gain block.

The third voltage term in the Kirchoff equation is the control input, V. We will apply a
step input.

Insert a Step block (from the Sources block library) and connect it with a line to
the positive input of the current Sum block.
To view the output speed, insert a Scope (from the Sinks block library) connected
to the output of the second rotational integrator (theta).
To provide a appropriate unit step input at t=0, double-click the Step block and set
the Step Time to "0".

You can download a model file for the complete system here.

Open-loop response
To simulate this system, first, an appropriate simulation time must be set. Select
Parameters from the Simulation menu and enter "0.2" in the Stop Time field. 0.2 seconds
is long enough to view the open-loop response. Also in the Parameters dialog box, it is
helpful to change the Solver Options method. Click on the field which currently contains
"ode45 (Dormand-Prince)". Select the option "ode15s (stiff/NDF)". Since the time scales
in this example are very small, this stiff system integration method is much more efficient
than the default integration method.

The physical parameters must now be set. Run the following commands at the MATLAB
prompt:
J=3.2284E-6;
b=3.5077E-6;
K=0.0274;
R=4;
L=2.75E-6;

Run the simulation (Ctrl-t or Start on the Simulation menu). When the simulation is
finished, double-click on the scope and hit its autoscale button. You should see the
following output.

Extracting a Digital Model into MATLAB


A linear digital model of this continuous-time system (in state space or transfer function
form) can be extracted from a Simulink model into MATLAB. Conversion to a discretetime (digital) system is done with Zero-Order Hold blocks on both the inputs and outputs
of the system, which act as both D/A (sample-and-hold) and A/D devices. The extraction
of a model makes use of In and Out Connection blocks and the MATLAB function
dlinmod. We will start with the model which we just build. You can download a complete
version here. We will first group all of the system components (except for the Step and
Scope which aren't really part of the system) into a Subsystem block.

Drag the mouse from one corner of your model window to the other to highlight
all of the components. If possible, avoid highlighting the Step and Scope blocks,
but if you do, hold the shift key and single click on either of the Step and Scope
blocks to un-highlight them. Your model window should appear as shown below.

Select Create Subsystem on the Edit menu (or hit Ctrl-G). This will group all of
the selected blocks into a single block. Your window should appear as shown
below.

Change the label of the Subsystem block to "Continuous Plant". If you like, you
can resize this block so the words "In1" and "Out1" inside of it don't overlap. To
resize a block, highlight it by single clicking it and drag the corners to the desired
size.
Replace the Step Block and Scope Block with Zero Order Hold blocks (from the
Discrete block library). One Zero Order Hold block is used to convert a discrete-

time signal to a stepwise-constant continuous signal. The other Zero Order Hold
block is used to take discrete samples of the output from the plant.
Edit the Zero Order Hold blocks and set the Sample Time fields to 0.001 (this is
fast compared to the desired step response in the MATLAB tutorial.)
Connect an In Connection Block to the input of the first Zero Order Hold block,
and an Out Connection Block to the output of the second Zero Order Hold block.
(these blocks can be found in the Connections block library). This defines the
input and output of the system for the extraction process.
Drag each block in your model so that they are arranged in a line.

Save your file as "motorpos.mdl" (select Save As from the File menu). MATLAB will
extract the linear model from the saved model file, not from the open model window. At
the MATLAB prompt, enter the following commands:
[A,B,C,D]=dlinmod('motorposmodel',.001)
[num,den]=ss2tf(A,B,C,D)

The extra parameter in dlinmod provides the sample time for the discrete conversion. You
should see the following output, providing discrete time models of the system both in
state-space and transfer function form.
A =

1.0000
0
0

0.0000
0.0000
0.0055

B =
0.0010
0.2359
2.0589
C =
1

0.0010
-0.0065
0.9425

D =
0
num =
0

0.0010

0.0010

0.0000

1.0000

-1.9425

0.9425

den =

As noticed in above results, both numerator and denominator of the discrete transfer
function have one extra root at z = 0. These cancel each other, and the discrete-time
transfer function to the motor position output from the voltage input is:

To verify the model extraction, we will generate an open-loop step response of the
extracted transfer function in MATLAB. Enter the following commands in MATLAB.
[x1] = dstep(num,den,201);
t=0:0.001:0.2;
stairs(t,x1)

You should see the following plot which is equivalent to the Scope's output.

Implementing Digital Control

In the motor speed control digital example a digital controller was designed with the
following transfer function.

Bring up the model window containing the digital system which was just
extracted into MATLAB. (You can download our version here)
Delete the "In" and "Out" blocks.

We will first feed back the plant output.

Insert a Sum block and assign "+-" to it's inputs.


Tap a line of the output line of the output Zero Order Hold line and draw it to the
negative input of the Sum block.

The output of the Sum block will provide the error signal. We will feed this into the
digital controller.

Insert a Discrete Transfer Function Block (from the Discrete block library) after
the summer and connect them with a line.
Edit this block and change the Numerator field to "450*conv([1 -.85],[1 -.85])",
the Denominator field to "conv([1 .98],[1 -.7])", and the Sample Time to ".001".

Label this block "Controller" and resize it to view the entire contents.

Finally, we will apply a step input and view the output on a scope.

Attach a Step block to the free input of the feedback Sum block and attach a
Scope block to the plant output.
Double-click the Step block and set the Step Time to "0".

You can download our version of the closed-loop system here.

Closed-loop response
To simulate this system, first, an appropriate simulation time must be set. Select
Parameters from the Simulation menu and enter "0.05" in the Stop Time field. The design
requirements included a settling time of less than 0.04 sec, so we simulate for 0.05 sec to
view the output. The physical parameters must now be set. Run the following commands
at the MATLAB prompt:
J=3.2284E-6;
b=3.5077E-6;
K=0.0274;
R=4;

L=2.75E-6;

Run the simulation (Ctrl-t or Start on the Simulation menu). When the simulation is
finished, double-click on the scope and hit its autoscale button. You should see the
following output.

Example: Bus Suspension Modeling in


Simulink
Physical setup
Building the model
Open-loop response
Extracting the Model
Implementing Full State Feedback
Closed-loop response

Physical setup
Designing an automatic suspension system for a bus turns out to be an interesting control
problem. When the suspension system is designed, a 1/4 bus model (one of the four
wheels) is used to simplify the problem to a one dimensional spring-damper system. A
diagram of this system is shown below:

Where:
* body mass (m1) = 2500 kg,
* suspension mass (m2) = 320 kg,
* spring constant of suspension system(k1) = 80,000 N/m,
* spring constant of wheel and tire(k2) = 500,000 N/m,
* damping constant of suspension system(b1) = 350 Ns/m.
* damping constant of wheel and tire(b2) = 15,020 Ns/m.
* control force (u) = force from the controller we are going to design.

Design requirements:
A good bus suspension system should have satisfactory road holding ability, while still
providing comfort when riding over bumps and holes in the road. When the bus is
experiencing any road disturbance (i.e. pot holes, cracks, and uneven pavement),the bus
body should not have large oscillations, and the oscillations should dissipate quickly.
Since the distance X1-W is very difficult to measure, and the deformation of the tire (X2W) is negligible, we will use the distance X1-X2 instead of X1-W as the output in our
problem. Keep in mind that this is an estimation.
The road disturbance (W) in this problem will be simulated by a step input. This step
could represent the bus coming out of a pothole. We want to design a feedback controller
so that the output (X1-X2) has an overshoot less than 5% and a settling time shorter than
5 seconds. For example, when the bus runs onto a 10 cm high step, the bus body will
oscillate within a range of +/- 5 mm and return to a smooth ride within 5 seconds.

Building the Model


This system will be modeled by summing the forces acting on both masses (body and
suspension) and integrating the accelerations of each mass twice to give velocities and
positions. Newton's law will be applied to each mass. Open Simulink and open a new
model window. First, we will model the integrals of the accelerations of the masses.

Insert an Integrator block (from the Linear block library) and draw lines to and
from its input and output terminals.
Label the input line "a1" (for acceleration) and the output line "v1" (for velocity)
To add such a label, double click in the empty space just above the line.
Insert another Integrator block connected to the output of the first.
Draw a line from its output and label it "x1" (for position).
Insert a second pair of Integrators below the first with lines labeled "a2", "v2",
and "x2".

Next, we will start to model Newton's law. Newton's law for each of these masses can be
expressed as:

These equations can be represented with gain blocks (for 1/M1 and 1/M2) and two
summation blocks.
Insert two Gain blocks, (from the Linear block library) one attached to the inputs
of each of the integrator pairs.
Edit the gain block corresponding to M1 by double-clicking it and changing its
value to "1/m1".
Change the label of this Gain block to "Mass 1" by clicking on the word "Gain"
underneath the block.
Similarly, edit the other Gain's value to "1/m2" and it's label to "Mass 2". (You
may want to resize the gain blocks to view the contents. To do this, single click on
the block to highlight it, and drag one of the corners to the desired size.)
There are three forces acting on M1 (one spring, one damper, and the input, u) and five
forces acting on M2 (two springs, two dampers, and the input, u).
Insert two Sum blocks (from the Linear block library), one attached by a line to
each of the Gain blocks.
Edit the signs of the Sum block corresponding to M1 to "+--" to represent the
three forces (two of which will be negative)
Edit the signs of the other Sum block to "++-++" to represent the five forces, one
of which will be negative.

Now, we will add in the forces acting on each mass. First, we will add in the force from
Spring 1. This force is equal to a constant, k1 times the difference X1-X2.

Insert a sum block after the upper pair of integrators.

Edit its signs to "+-" and connect the "x1" signal to the positive input and the "x2"
signal to the negative input.
Draw a line leading from the output of the Sum block.
Insert a Gain block above the "Mass1" block.
Flip it left-to-right by single-clicking on it and selecting Flip Block from the
Format menu (or hit Ctrl-F).
Edit the value of this gain to "k1" and label the block "Spring 1".
Tap a line off the output of the last Sum block and connect it to the input of this
gain block.
Connect the output of this gain block (the spring force) to the second input of the
Mass 1 Sum block. This input should be negative since the Spring 1 pulls down
on Mass 1 when X1 > X2.
Tap a line off the spring force line and connect it to the second input of the Mass 2
Sum block. This input is positive since Spring 1 pulls up on Mass 2.

Now, we will add in the force from Damper 1. This force is equal to b1 times V1-V2.

Insert a sum block below the Mass 1's first integrator.


Flip it left-to-right, and edit it's signs to "+-".
Tap a line off the "v1" line and connect it to the positive input of this Sum block.
Tap a line off the "v2" line and connect it to the negative input of this Sum block.
Insert a Gain block to the left of this Sum block and flip it left-to-right.
Edit it's value to "b1" and label it "Damper 1".
Connect the output of the new Sum block to the input of this gain block.

Connect the output of this gain block (the damper force) to the third input of the
Mass 1 Sum block. This input is negative, similar to Spring 1's force on Mass 1.
Tap a line off Damper 1's force line and connect it to the first input (which is
positive) of Mass 2's Sum block.

Now we will add in the force from Spring 2. This force acts only on Mass 2, but depends
on the ground profile, W. Spring 2's force is equal to X2-W.

Insert a Step block in the lower left area of your model window. Label it "W".
Edit it's Step Time to "0" and it's Final Value to "0". (We will assume a flat road
surface for now).
Insert a Sum block to the right of the W Step block and edit its signs to "-+".
Connect the output of the Step block to the positive input of this Sum block.
Tap a line off the "x2" signal and connect it to the negative input of the new Sum
block.
Insert a Gain block to the right of this Sum block and connect the Sum's output to
the new Gain's input.
Change the value of the gain to "k2" and label it "Spring 2".
Connect the output of this block (Spring 2's force) to the fourth input of Mass 2's
Sum block. This force adds in in the positive sense.

Next, we will add in the force from Damper 2. This force is equal to b2 times V2d/dt(W). Since there is no existing signal representing the derivative of W we will need
to generate this signal.

Insert a Derivative block (from the Linear block library) to the right of the W step
block.
Tap a line of the Step's output and connect it to the input of the Derivative block.
Insert a Sum block after the Derivative block and edit it's signs to "+-".
Connect the Derivative's output to the positive input of the new Sum block.
Tap a line off the "v2" line and connect it to the negative input of this Sum block.
Connect the output of this Sum block (Damper 2's force) to the fifth input of Mass
2's Sum block. This force also adds in with positive sign.

The last force in the input U acting between the two masses.

Insert a Step block in the upper left of the model window.


Connect it's output to the remaining input of Mass 1's Sum block (with positive
sign).
Tap a line off this signal and connect it to the remaining input of Mass 2's Sum
block (with negative sign).
Edit this Step block's Step Time to "0" and leave its Final Value "1".
Label this Step block "U".
Finally, to view the output (X1-X2) insert a Scope connected to the output of the
rightmost Sum block.

You can download a model file for the complete system here.

Open-loop response
To simulate this system, first, an appropriate simulation time must be set. Select
Parameters from the Simulation menu and enter "50" in the Stop Time field. 50 seconds
is long enough to view the open-loop response. The physical parameters must now be set.
Run the following commands at the MATLAB prompt:
m1=2500;
m2=320;
k1=80000;
k2=500000;
b1 = 350;
b2 = 15020;

Run the simulation (Ctrl-t or Start on the Simulation menu). When the simulation is
finished, double-click on the scope and hit its autoscale button. You should see the
following output.

Extracting a Linear Model into MATLAB


A linear model of the system (in state space or transfer function form) can be extracted
from a Simulink model into MATLAB. This is done through the use of In and Out
Connection blocks and the MATLAB function linmod. We will extract only the model
from the input U to the output X1-X2.

First, replace the U Step block with an In Connection Block.


Also, replace the Scope block with an Out Connection Block. (These blocks can
be found in the Connections block library). This defines the input and output of
the system for the extraction process.

Save your file as "suspmod.mdl" (select Save As from the File menu). MATLAB will
extract the linear model from the saved model file, not from the open model window. At
the MATLAB prompt, enter the following commands:
[A,B,C,D]=linmod('suspmodel')
[num,den]=ss2tf(A,B,C,D)

You should see the following output, providing both state-space and transfer function
models of the system.
A =
1.0e+003 *
0
0
0.2500
-0.0320

0
0
-1.8125
0.0320

0
0.0010
-0.0480
0.0001

B =
0
0
-0.0031
0.0004
C =
1

-1

0.0010
0
0.0011
-0.0001

D =
0
num =
0

0.0000

0.0035

0.0188

0.6250

0.0048

0.1851

0.1721

5.0000

den =
1.0e+004 *
0.0001

To verify the model extraction, we will generate an open-loop step response of the
extracted transfer function in MATLAB. Enter the following command in MATLAB.
step(num,den);

You should see the following plot which is equivalent to the Scope's output.

Implementing Full State Feedback


In the Bus Suspension Control State Space example a full-state feedback controller was
designed feeding back the following five states:
The controller used the following feedback gain matrix:

To implement this in Simulink, we will contain the open-loop system from earlier in this
page in a Subsystem block.
Create a new model window.
Drag a Subsystem block from the Connections block library into your new model
window.

Double click on this block. You will see a blank window representing the contents
of the subsystem (which is currently empty).
Open your previously saved model of the Bus Suspension system, suspmod.mdl.
Select Select All from the Edit menu (or Ctrl-A), and select Copy from the Edit
menu (or Ctrl-C).
Select the blank subsystem window from your new model and select Paste from
the Edit menu (or Ctrl-V). You should see your original system in this new
subsystem window (you may need to use the scroll bars to center on it).
Label the In Connection block "U", and the Out Connection block "y1".
Replace the W Step block with an In Connection block and label this block "W".

Now we will generate the other state outputs from the subsystem.

Insert an Out block below the "y1" block and label it "d/dt(y1)", Tap a line off the
line leading into the Damper 1 gain block (V1-V2) and connect it to the d/dt(y1)
Out block.
Insert another Out block below the "d/dt(y1)" Out block and label it "x1".
Tap a line off the "x1" line and connect it to this Out block.
Insert another Out block below the "x1" Out block and label it "d/dt(x1)".
Tap a line off the "v1" line and connect it to this Out block.

The final, extra, state needs to be generated, which is the integral of Y1.

Insert an Integrator block above the "y1" Out block and connect its input with a
line tapped of the input to the "y1" Out block.
Insert an Out block, label it "int(y1)", and connect it to the output of the new
integrator.

Since the state outputs will be used to form a vector, it is important that they be numbered
in the right order.

Edit the "x1" Out block and change its Port Number to "1".
Similarly, change the "d/dt(x1)" Out block's port number to "2", "y1" Out's port
number to "3", "d/dt(y1)" Out's port number to "4", and "int(y1)" Out's port
number to "5".
The In blocks should be numbered such that "U" is "1" and "W" is "2". Some of
these numbers may already be correct.

Close the Subsystem window. You should now see input and output terminals on
the Subsystem block.
Name this block "Suspension Model".
You should resize this block so that you can read all of the labels. To do this,
highlight it by single-clicking on it and drag one of the highlighted corners to the
right size. Notice that the model has two inputs and five outputs. Each input and
output is a scalar signal in this model.

Now, we will build a full-state feedback controller around the plant model. First, we need
to create a vector signal out of the five scalar outputs in order to multiply by the feedback
gain matrix K.

Insert a Mux block (from the Connections block library) to the right of the
Suspension Model block. The Mux takes multiple inputs and combines them into
a vector signal. By default, the Mux has three inputs.
Edit the Mux block and change the Number of Inputs to "5".
Resize the Mux so that it is the same height as the Suspension Model block.
Connect each of the Suspension Model's outputs to the Mux's inputs in order.

Now, we will close the loop.

Insert a Matrix Gain block (from the Linear block library) below the Suspension
Model block.
Flip the Matrix Gain left-to-right and edit its value to "K".
Insert a Sum block to the left of the Suspension Model block.
Edit its signs to "+-".
Connect the output of the Matrix Gain to the negative input of the Sum block.
Connect the output of the Sum block to the "U" input of the Suspension Model.

Insert a Step block and connect it to the positive input of the Sum block.
Label the step block "r" and edit its Step Time to "0" and its Final Value to "0"
(we are commanding the bust to stay level).
Insert a Step block and connect it to the "W" input of the Suspension Model.
Edit its Step Time to "0" and its Final Value to "-.1" (we are now assuming a
10cm deep pothole).
Insert a Scope block and tap a line off the "y1" output of the Suspension Model
and connect it to the Scope.

You can download our version of the closed-loop system here.

Closed-loop response
To simulate this system, first, an appropriate simulation time must be set. Select
Parameters from the Simulation menu and enter "2" in the Stop Time field. The design

requirements included a settling time of less than 5 sec, and the system actually settles in
2 sec. The physical parameters must now be set. Run the following commands at the
MATLAB prompt:
m1=2500;
m2=320;
k1=80000;
k2=500000;
b1 = 350;
b2 = 15020;

The last step is to assign values to the feedback gain matrix K. Execute the following
command at the MATLAB prompt.
K= [ 0 2.3e6 5e8 0 8e6 ];

Run the simulation (Ctrl-t or Start on the Simulation menu). When the simulation is
finished, double-click on the scope and hit its autoscale button. You should see the
following output.

Example: Modeling an Inverted Pendulum


in Simulink
Problem setup and design requirements
Force analysis and system equation setup
Building the model
Open-loop response
Extracting a linearized model
Implementing PID control
Closed-loop response

Problem setup and design requirements

The cart with an inverted pendulum, shown below, is "bumped" with an impulse force, F.
Determine the dynamic equations of motion for the system, and linearize about the
pendulum's angle, theta = 0 (in other words, assume that pendulum does not move more
than a few degrees away from the vertical, chosen to be at an angle of 0). Find a
controller to satisfy all of the design requirements given below.

For this example, let's assume that


M
m
b
l
I
F
x
theta

mass of the cart


0.5 kg
mass of the pendulum
0.2 kg
friction of the cart
0.1 N/m/sec
length to pendulum center of mass 0.3 m
inertia of the pendulum
0.006 kg*m^2
force applied to the cart
cart position coordinate
pendulum angle from vertical

In this example, we will implement a PID controller which can only be applied to a
single-input-single-output (SISO) system,so we will be only interested in the control of
the pendulums angle. Therefore, none of the design criteria deal with the cart's position.
We will assume that the system starts at equilibrium, and experiences an impulse force of
1N. The pendulum should return to its upright position within 5 seconds, and never move
more than 0.05 radians away from the vertical.
The design requirements for this system are:

Settling time of less than 5 seconds.


Pendulum angle never more than 0.05 radians from the vertical.

Force analysis and system equation setup

Below are the two Free Body Diagrams of the system.

This system is tricky to model in Simulink because of the physical constraint (the pin
joint) between the cart and pendulum which reduces the degrees of freedom in the
system. Both the cart and the pendulum have one degree of freedom (X and theta,
respectively). We will then model Newton's equation for these two degrees of freedom.

It is necessary, however, to include the interaction forces N and P between the cart and
the pendulum in order to model the dynamics. The inclusion of these forces requires
modeling the x and y dynamics of the pendulum in addition to its theta dynamics. In the
MATLAB tutorial pendulum modeling example the interaction forces were solved for
algebraically. Generally, we would like to exploit the modeling power of Simulink and let
the simulation take care of the algebra. Therefore, we will model the additional x and y
equations for the pendulum.

However, xp and yp are exact functions of theta. Therefore, we can represent their
derivatives in terms of the derivatives of theta.

These expressions can then be substituted into the expressions for N and P. Rather than
continuing with algebra here, we will simply represent these equations in Simulink.
Simulink can work directly with nonlinear equations, so it is unnecessary to linearize
these equations as it was in the MATLAB tutorials.

Building the Model in Simulink


First, we will model the states of the system in theta and x. We will represent Newton's
equations for the pendulum rotational inertia and the cart mass.
Open a new model window in Simulink, and resize it to give plenty of room (this
is a large model).
Insert two integrators (from the Linear block library) near the bottom of your
model and connect them in series.
Draw a line from the second integrator and label it "theta". (To insert a label,
double-click where you want the label to go.)

Label the line connecting the integrators "d/dt(theta)".


Draw a line leading to the first integrator and label it "d2/dt2(theta)".
Insert a Gain block (from the Linear block library) to the left of the first integrator
and connect its output to the d2/dt2(theta) line.
Edit the gain value of this block by double clicking it and change it to "1/I".
Change the label of this block to "Pendulum Inertia" by clicking on the word
"Gain". (you can insert a newline in the label by hitting return).
Insert a Sum block (from the Linear block library) to the left of the Pendulum
Inertia block and connect its output to the inertia's input.
Change the label of this block to Sum Torques on Pend.
Construct a similar set of elements near the top of your model with the signals
labeled with "x" rather than "theta". The gain block should have the value "1/M"
with the label "Cart Mass", and the Sum block should have the label "Sum Forces
on Cart".
Edit the Sum Forces block and change its signs to "-+-". This represents the signs
of the three horizontal forces acting on the cart.

Now, we will add in two of the forces acting on the cart.

Insert a Gain block above the Cart Mass block. Change its value to "b" and its
label to "damping".
Flip this block left-to-right by single clicking on it (to select it) and selecting Flip
Block from the Format menu (or hit Ctrl-F).
Tap a line off the d/dt(x) line (hold Ctrl while drawing the line) and connect it to
the input of the damping block.
Connect the output of the damping block to the topmost input of the Sum Forces
block. The damping force then has a negative sign.
Insert an In block (from the Connections block library) to the left of the Sum
Forces block and change its label to "F".
Connect the output of the F in block to the middle (positive) input of the Sum
Forces block.

Now, we will apply the forces N and P to both the cart and the pendulum. These forces
contribute torques to the pendulum with components "N L cos(theta) and P L sin(theta)".
Therefore, we need to construct these components.

Insert two Elementary Math blocks (from the Nonlinear block library) and place
them one above the other above the second theta integrator. These blocks can be
used to generate simple functions such as sin and cos.
Edit upper Math block's value to "cos" and leave the lower Math block's value
"sin".
Label the upper (cos) block "Vertical" and the lower (sin) block "Horizontal" to
identify the components.
Flip each of these blocks left-to-right.
Tap a line off the theta line and connect it to the input of the cos block.
Tap a line of the line you just drew and connect it to the input of the sin block.
Insert a Gain block to the left of the cos block and change its value to "l"
(lowercase L) and its label to "Pend. Len."
Flip this block left-to-right and connect it to the output of the cos block.
Copy this block to a position to the left of the sin block. To do this, select it (by
single-clicking) and select Copy from the Edit Menu and then Paste from the Edit
menu (or hit Ctrl-C and Ctrl-V). Then, drag it to the proper position.
Connect the new Pend. Len.1 block to the output of the sin block.
Draw long horizontal lines leading from both these Pend. Len. blocks and label
the upper one "l cos(theta)" and the lower one "l sin(theta)".

Now that the pendulum components are available, we can apply the forces N and P. We
will assume we can generate these forces, and just draw them coming from nowhere for
now.

Insert two Product blocks (from the Nonlinear block library) next to each other to
the left and above the Sum Torques block. These will be used to multiply the
forces N and P by their appropriate components.
Rotate the left Product block 90 degrees. To do this, select it and select Rotate
Block from the Format menu (or hit Ctrl-R).
Flip the other product block left-to-right and also rotate it 90 degrees.
Connect the left Product block's output to the lower input of the Sum Torques
block.
Connect the right Product block's output to the upper input of the Sum Torques
block.
Continue the l cos(theta) line and attach it to the right input of the left Product
block.
Continue the l sin(theta) line and attach it to the right input of the right Product
block.

Begin drawing a line from the open input of the right product block. Extend it up
and the to the right. Label the open end of this line "P".
Begin drawing a line from the open input of the left product block. Extend it up
and the to the right. Label the open end of this line "N".
Tap a line off the N line and connect it to the open input of the Sum forces block.

Next, we will represent the force N and P in terms of the pendulum's horizontal and
vertical accelerations from Newton's laws.

Insert a Gain block to the right of the N open ended line and change its value to
"m" and its label to "Pend. Mass".
Flip this block left-to-right and connect it's to N line.
Copy this block to a position to the right of the open ended P line and attach it to
the P line.
Draw a line leading to the upper Pend. Mass block and label it "d2/dt2(xp)".
Insert a Sum block to the right of the lower Pend. Mass block.
Flip this block left-to-right and connect its output to the input of the lower Pend.
Mass block.

Insert a Constant block (from the Sources block library) to the right of the new
Sum block, change its value to "g" and label it "Gravity".
Connect the Gravity block to the upper (positive) input of the newest Sum block.
Draw a line leading to the open input of the new Sum block and label it
"d2/dt2(yp)".

Now, we will begin to produce the signals which contribute to d2/dt2(xp) and d2/dt2(yp).

Insert a Sum block to the right of the d2/dt2(yp) open end.


Change the Sum block's signs to "--" to represent the two terms contributing to
d2/dt2(yp).
Flip the Sum block left-to-right and connect it's output to the d2/dt2(yp) signal.
Insert a Sum block to the right of the d2/dt2(xp) open end.
Change the Sum block's signs to "++-" to represent the three terms contributing to
d2/dt2(xp).
Flip the Sum block left-to-right and connect it's output to the d2/dt2(xp) signal.
The first term of d2/dx2(xp) is d2/dx2(x). Tap a line off the d2/dx2(x) signal and
connect it to the topmost (positive) input of the newest Sum block.

Now, we will generate the terms d2/dt2(theta)*lsin(theta) and d2/dt2(theta)*lcos(theta).

Insert two Product blocks next to each other to the right and below the Sum block
associated with d2/dt2(yp).
Rotate the left Product block 90 degrees.
Flip the other product block left-to-right and also rotate it 90 degrees.
Tap a line off the l sin(theta) signal and connect it to the left input of the left
Product block.
Tap a line off the l cos(theta) signal and connect it to the right input of the right
Product block.
Tap a line off the d2/dt2(theta) signal and connect it to the right input of the left
Product block.
Tap a line of this new line and connect it to the left input of the right Product
block.

Now, we will generate the terms (d/dt(theta))^2*lsin(theta) and


(d/dt(theta))^2*lcos(theta).

Insert two Product blocks next to each other to the right and slightly above the
previous pair of Product blocks.
Rotate the left Product block 90 degrees.
Flip the other product block left-to-right and also rotate it 90 degrees.
Tap a line off the l cos(theta) signal and connect it to the left input of the left
Product block.
Tap a line off the l sin(theta) signal and connect it to the right input of the right
Product block.
Insert a third Product block and insert it slightly above the d/dt(theta) line. Label
this block "d/dt(theta)^2".
Tap a line off the d/dt(theta) signal and connect it to the left input of the lower
Product block.
Tap a line of this new line and connect it to the right input of the lower Product
block.

Connect the output of the lower Product block to the free input of the right upper
Product block.
Tap a line of this new line and connect it to the free input of the left upper Product
block.

Finally, we will connect these signals to produce the pendulum acceleration signals. In
addition, we will create the system outputs x and theta.

Connect the d2/dt2(theta)*lsin(theta) Product block's output to the lower


(negative) input of the d2/dt2(yp) Sum block.
Connect the d2/dt2(theta)*lcos(theta) Product block's output to the lower
(negative) input of the d2/dt2(xp) Sum block.
Connect the d/dt(theta)^2*lcos(theta) Product block's output to the upper
(negative) input of the d2/dt2(yp) Sum block.
Connect the d/dt(theta)^2*lsin(theta) Product block's output to the middle
(positive) input of the d2/dt2(xp) Sum block.
Insert an Out block (from the Connections block library) attached to the theta
signal. Label this block "Theta".

Insert an Out block attached to the x signal. Label this block "x". It should
automatically be numbered 2.

Now, save this model as pend.mdl.

Open-loop response
To generate the open-loop response, it is necessary to contain this model in a subsystem
block.
Create a new model window (select New from the File menu in Simulink or hit
Ctrl-N).
Insert a Subsystem block from the Connections block library.
Open the Subsystem block by double clicking on it. You will see a new model
window labeled "Subsystem".
Open your previous model window named pend.mdl. Select all of the model
components by selecting Select All from the Edit menu (or hit Ctrl-A).

Copy the model into the paste buffer by selecting Copy from the Edit menu (or hit
Ctrl-C).
Paste the model into the Subsystem window by selecting Paste from the Edit
menu (or hit Ctrl-V) in the Subsystem window
Close the Subsystem window. You will see the Subsystem block in the untitled
window with one input terminal labeled F and two output terminals labeled Theta
and x.
Resize the Subsystem block to make the labels visible by selecting it and dragging
one of the corners.
Label the Subsystem block "Inverted Pendulum".

Now, we will apply a unit impulse force input, and view the pendulum angle and cart
position. An impulse can not be exactly simulated, since it is an infinite signal for an
infinitesimal time with time integral equal to 1. Instead, we will use a pulse generator to
generate a large but finite pulse for a small but finite time. The magnitude of the pulse
times the length of the pulse will equal 1.

Insert a Pulse Generator block from the Sources block library and connect it to the
F input of the Inverted Pendulum block.
Insert a Scope block (from the Sinks block library) and connect it to the Theta
output of the Inverted Pendulum block.
Insert a Scope block and connect it to the x output of the Inverted Pendulum
block.
Edit the Pulse Generator block by double clicking on it. You will see the
following dialog box.

Change the Period value to "10" (a long time between a chain of impulses - we
will be interested in only the first pulse).
Change the Duty Cycle value to ".01" this corresponds to .01% of 10 seconds, or .
001 seconds.
Change the Amplitude to 1000. 1000 times .001 equals 1, providing an
approximate unit impulse.
Close this dialog box. You system will appear as shown below.

We now need to set an appropriate simulation time to view the response.

Select Parameters from the Simulation menu.


Change the Stop Time value to 2 seconds.
Close this dialog box

You can download a version of the system here. Before running it, it is necessary to set
the physical constants. Enter the following commands at the MATLAB prompt.
M = .5;

m
b
i
g
l

=
=
=
=
=

0.2;
0.1;
0.006;
9.8;
0.3;

Now, start the simulation (select Start from the Simulation menu or hit Ctrl-t). If you look
at the MATLAB prompt, you will see some error messages concerning algebraic loops.
Due to the algebraic constraint in this system, there are closed loops in the model with no
dynamics which must be resolved completely at each time step before dynamics are
considered. In general, this is not a problem, but often algebraic loops slow down the
simulation, and can cause real problems if discontinuities exist within the loop (such as
saturation, sign functions, etc.)
Open both Scopes and hit the autoscale buttons. You will see the following for theta (left)
and x (right).

Notice that the pendulum swings all the way around due to the impact, and the cart
travels along with a jerky motion due to the pendulum. These simulations differ greatly

from the MATLAB open loop simulations because Simulink allows for fully nonlinear
systems.

Extracting the linearized model into MATLAB


Since MATLAB can't deal with nonlinear systems directly, we cannot extract the exact
model from Simulink into MATLAB. However, a linearized model can be extracted. This
is done through the use of In and Out Connection blocks and the MATLAB function
linmod. In the case of this example, will use the equivalent command linmod2, which can
better handle the numerical difficulties of this problem.
To extract a model, it is necessary to start with a model file with inputs and outputs
defined as In and Out blocks. Earlier in this tutorial this was done, and the file was saved
as pend.mdl. In this model, one input, F (the force on the cart) and two outputs, theta
(pendulum angle from vertical) and x (position of the cart), were defined. When
linearizing a model, it is necessary to choose an operating point about which to linearize.
By default, the linmod2 command linearizes about a state vector of zero and zero input.
Since this is the point about which we would like to linearize, we do not need to specify
any extra arguments in the command. Since the system has two outputs, we will generate
two transfer functions.
At the MATLAB prompt, enter the following commands
[A,B,C,D]=linmod2('pend')
[nums,den]=ss2tf(A,B,C,D)
numtheta=nums(1,:)
numx=nums(2,:)

You will see the following output (along with algebraic loop error messages) providing a
state-space model, two transfer function numerators, and one transfer function
denominator (both transfer functions share the same denominator).
A =
0
0
31.1818
2.6727

0
0
0.0000
0.0000

1.0000
0
0.0000
0.0000

B =
0
0
4.5455
1.8182
C =
1
0

0
1

0
0

0
0

0
1.0000
-0.4545
-0.1818

D =
0
0
nums =
0
0

0.0000
0.0000

4.5455
1.8182

0.0000
0.0000

0.0000
-44.5455

1.0000

0.1818

-31.1818

-4.4545

0.0000

0.0000

4.5455

0.0000

0.0000

0.0000

1.8182

0.0000

-44.5455

den =

numtheta =

numx =

To verify the model, we will generate an open-loop response. At the MATLAB command
line, enter the following commands.
t=0:0.01:5;
impulse(numtheta,den,t);
axis([0 1 0 60]);

You should get the following response for the angle of the pendulum.

Note that this is identical to the impulse response obtained in the MATLAB tutorial
pendulum modeling example. Since it is a linearized model, however, it is not the same
as the fully-nonlinear impulse response obtained in Simulink.

Implementing PID control


In the pendulum PID control example, a PID controller was designed with proportional,
integral, and derivative gains equal to 100, 1, and 20, respectively. To implement this, we
will start with our open-loop model of the inverted pendulum. And add in both a control
input and the disturbance impulse input to the plant.
Open your Simulink model window you used to obtain the nonlinear open-loop
response. (pendol.mdl)
Delete the line connecting the Pulse Generator block to the Inverted Pendulum
block. (single-click on the line and select Cut from the Edit menu or hit Ctrl-X).
Move the Pulse Generator block to the upper left of the window.
Insert a Sum block to the left of the Inverted Pendulum block.
Connect the output of the Sum block to the Inverted Pendulum block.
Connect the Pulse generator to the upper (positive) input of the Sum block.

Now, we will feed back the angle output.

Insert a Sum block to the right and below the Pulse Generator block.
Change the signs of the Sum block to "+-".
Insert a Constant block (from the Sources block library) below the Pulse
generator. Change its value to "0". This is the reference input.
Connect the constant block to the upper (positive) input of the second Sum block.
Tap a line off the Theta output of the Inverted Pendulum block and draw it down
and to the left. Extend this line and connect it to the lower (negative) input of the
second Sum block.

Now, we will insert a PID controller.

Double-click on the Blocksets & Toolboxes icon in the main Simulink window.
This will open a new window with two icons.
In this new window, double-click on the SIMULINK extras icon. This will open a
window with icons similar to the main Simulink window.
Double-click on the Additional Linear block library icon. This will bring up a
library of Linear blocks to augment the standard Linear block library.
Drag a PID Controller block into your model between the two Sum blocks.
Connect the output of the second Sum block to the input of the PID block.
Connect the PID output to the first Sum block's free input.

Edit the PID block by doubleclicking on it.


Change the Proportional gain to 100, leave the Integral gain 1, and change the
Derivative gain to 20.
Close this window.

You can download our version of the closed-loop system here

Closed-loop response
We can now simulate the closed-loop system. Be sure the physical parameters are set (if
you just ran the open-loop response, they should still be set.) Start the simulation, doubleclick on the Theta scope and hit the autoscale button. You should see the following
response:

This is identical to the closed-loop response obtained in the MATLAB tutorials. Note that
the PID controller handles the nonlinear system very well because the angle is very small
(.04 radians).

Example: Modeling a Pitch Controller in


Simulink
Physical setup and system equations
Building the State-Space Model
Open-loop response
Extracting the model into MATLAB
Building a full-state feedback controller
Closed-loop response

Physical setup and system equations


The equations governing the motion of an aircraft are a very complicated set of six nonlinear coupled differential equations. However, under certain assumptions, they can be
decoupled and linearized into the longitudinal and lateral equations. Pitch control is a
longitudinal problem, and in this example, we will design an autopilot that controls the
pitch of an aircraft. In this example, we will begin with the linearized state-space
equation model which was obtained in the MATLAB Tutorials: pitch control example This
model, with numerical values substituted in, is as follows:

in state-space form, the equations are as follows:

Which can be written as:

Building the state-space model


We will model these state equations explicitly in Simulink taking advantage of vector
lines to carry the state vector signal X. Vector lines are produced automatically in
Simulink when blocks input or output vector signals. First, we will represent the
derivative of the state.
Open a new model window in Simulink.
Insert an Integrator block from the Linear block library.
Draw a line from the output of the Integrator and label it "X". To label a line,
double click near the line where you want the label to appear.
Draw a line leading to the input of the Integrator and label it "d/dt(X)"

Now, we will represent the first state equation, which is d/dt(X)=Ax+Bu.

Insert a Matrix Gain block from the Linear block library below the integrator.
Flip this block left-to-right. To do this, select it with the mouse (single-click) and
select Flip Block from the Format menu (or hit Ctrl-F).
Edit the Matrix Gain block (by double clicking). Change the Gain Matrix field to
"A" (which we will define later in MATLAB) and close the dialog box.
Change the label of this block from Matrix Gain to "A" by single clicking on the
existing label.
Tap a line off the state signal, X (hold Ctrl while drawing the line to tap) and
connect it to the input of the A block. This creates the signal Ax.
Insert a Sum block (from the Linear block library) to the left of the integrator and
connect it's output to the line leading to the Integrator's input.
Draw a line from the output of the A matrix block to the lower (positive) input of
the Sum block.
Insert another Matrix Gain block to the left of the Sum block. Change it's Matrix
Gain value to "B" and change it's label to "B".
Connect the B matrix output to the other (positive) input of the Sum block.
Draw a line leading to the input of the Sum block. This is the input signal, u.

Now we will form the output signal which is equal to Cx+Du.

Insert a Matrix Gain block to the right of the integrator and attach the integrator's
output to the input of the Matrix Gain.
Change the Matrix Gain value to "C" and change it's label to "C".
Insert another Matrix Gain block below the "C" block, and change both it's value
and label to "D".
Tap a line off the u signal (the input line of the B matrix block) and attach it to the
input of the "D" matrix block.
Insert a Sum block to the right of the C matrix block.
Connect the outputs of the C and D matrix blocks to the inputs of the Sum block.

Next, we will apply inputs and extract outputs from this system. We will use In and Out
blocks for this purpose. These blocks allow the system to be extracted into MATLAB and
they allow the system to be placed into a Subsystem block for use within another model.

Insert an In block (from the Connections block library) and connect it to the open
line which connects to the input of the B matrix block.
Change the label of the In block to "deltac" (corresponding to the angle of the
elevator).

Insert an Out block (from the Connections block library) and connect it to the
output of the rightmost Sum block.
Change the label of this Out block to "theta" (corresponding to the pitch angle of
the plane).
Insert an Out block above the Theta block, and change it's label to "X"
corresponding to the state vector of the system. (This will be used later to
implement full-state feedback.
Tap a line off the X signal (leading from the second integrator) and connect it to
the X Out block.

Save this model as "pitch.mdl" (or download ours here.)

Open-loop response
To generate the open-loop response, it is first necessary to contain this model in a
subsystem block.
Create a new model window (select New from the File menu in Simulink or hit
Ctrl-N).
Insert a Subsystem block from the Connections block library.
Open the Subsystem block by double clicking on it. You will see a new model
window labeled "Subsystem".
Open your previous model window named pitch.mdl. Select all of the model
components by selecting Select All from the Edit menu (or hit Ctrl-A).
Copy the model into the paste buffer by selecting Copy from the Edit menu (or hit
Ctrl-C).
Paste the model into the Subsystem window by selecting Paste from the Edit
menu (or hit Ctrl-V) in the Subsystem window
Close the Subsystem window. You will see the Subsystem block in the untitled
window with one input terminal labeled deltac and two output terminals labeled
theta and x.
Resize the Subsystem block to make the labels visible by selecting it and dragging
one of the corners.

Label the Subsystem block "Plane Pitch Model".

Insert a Step block (from the Sources block library) and connect it to the input of
the Plane Pitch Model.
Edit the Step block (by double clicking on it to bring up the dialog box) and
change the Step Time value to 0. Close the Step block dialog box.
Insert a Scope block (from the Sinks block library) and connect it to the theta
output of the Plane Pitch Model.

Before obtaining a step response, we must set the constants in the matrices A, B, C, and
D. Enter the following commands at the MATLAB prompt.
A=[-0.313 56.7 0; -0.0139 -0.426 0; 0 56.7 0];
B=[0.232; 0.0203; 0];
C=[0 0 1];
D=[0];

We are now ready to run the simulation. If you like, you can download our version of the
open-loop system here. Start the simulation by selecting Start from the Simulation menu
(or hit Ctrl-t). When the simulation is finished, open the Scope by double clicking on it
and hit the Scope's autoscale button. You will see the following response.

Extracting the model into MATLAB


The Simulink model can be extracted into an equivalent state-space model in MATLAB.
This is done through the use of In and Out Connection blocks and the MATLAB function
linmod.
To extract a model, it is necessary to start with a model file with inputs and outputs
defined as In and Out blocks. Earlier in this tutorial this was done, and the file was saved
as pitch.mdl. In this model, one input, deltac (the elevator angle) and two outputs, theta
(pitch angle) and X (the state vector), were defined. We must truncate the output and
feedthrough matrices (Co and Do) to provide only the first input.
At the MATLAB prompt, enter the following commands
[Ao,Bo,Co,Do]=linmod('pitch');
Ao
Bo
Co=Co(1,:)
Do=Do(1,:)

You will see the following output providing the open-loop model of the system.
Ao =
-0.3130
-0.0139
0
Bo =
0.2320
0.0203
0

56.7000
-0.4260
56.7000

0
0
0

Co =
0

Do =
0

Note that the matrices Ao, Bo, Co, and Do are the same at the original matrices A, B,C,
and D.

Building a full-state feedback controller


In the CTMS Example: Pitch Controller -- State Space Method page, a full-state feedback
controller was designed using the LQR method. We will now construct this controller in
Simulink.
Bring up your open-loop Pitch model window (or download ours here)
Insert a Matrix Gain block below the Plane Pitch Model and change both its
Matrix Gain value and it's label to "K".
Flip the K matrix block left-to-right.
Insert a Sum block to the left of the Plane Pitch Model and change it's value to
"+-".
Connect the state vector X output of the Plane Pitch Model to the input of the K
matrix block.
Connect the output of the K matrix block to the second (negative) input of the
Sum block.
Connect the Step block to the first (positive) input of the Sum block.
Connect the Sum block's output to the input of the Plane Pitch Model.

You can download our version of the closed-loop model here.

Closed-loop response
Before simulating the closed-loop system, we must first determine the gain matrix K
using the LQR method. Execute the following commands at the MATLAB prompt.

p=50;
Q=[0 0 0;
0 0 0;
0 0 p];
[K]= lqr (A,B,Q,1)

Start the simulation in Simulink. Open the scope window and hit the Autoscale button.
You should see the following response.

Example: Modeling the Ball and Beam


Experiment in Simulink
Problem Setup and System Equations
Building the Simulink Model
Open-Loop Response
Extracting the Model into MATLAB
Constructing a Lead Compensator Controller
Closed-Loop Response

Problem Setup
A ball is placed on a beam, see figure below, where it is allowed to roll with 1 degree of
freedom along the length of the beam. A lever arm is attached to the beam at one end and
a servo gear at the other. As the servo gear turns by an angle theta, the lever changes the
angle of the beam by alpha. When the angle is changed from the horizontal position,
gravity causes the ball to roll along the beam. A controller will be designed for this
system so that the ball's position can be manipulated.

For this problem, we will assume that the ball rolls without slipping and friction between
the beam and ball is negligible. The constants and variab for this example are defined as
follows:
M
R
d
g
L
J
r
alpha
theta

mass of the ball


0.11 kg
radius of the ball
0.015 m
lever arm offset
0.03 m
gravitational acceleration 9.8 m/s^2
length of the beam
1.0 m
ball's moment of inertia 9.99e-6 kgm^2
ball position coordinate
beam angle coordinate
servo gear angle

The design criteria for this problem are:

Settling time less than 3 seconds


Overshoot less than 5%

The second derivative of the input angle alpha actually affects the second derivative of r.
However, we will ignore this contribution. The Lagrangian equation of motion for the
ball is then given by the following:

The beam angle (alpha) can be expressed in terms of the angle of the gear (theta).

Building the Model in Simulink


In this example, rather than express all the forces and geometric constraints (which is
difficult to model in Simulink for dynamic systems with constraints) we will model the
nonlinear Lagrangian equation of motion directly. This equation gives d/dt(r) as a
function of the state and input variab, r, d/dt(r), alpha, and d/dt(alpha). We will make use
of the Nonlinear Function Block to express this function. First, we must express the
derivatives of the output, r.
Open a new model window in Simulink.
Insert an Integrator block from the Linear block library.
Insert a second Integrator to the right of the first, and connect the two with a line.
Label the line connecting the two "d/dt(r)". To label a line, double-click near the
line where you want the label (in this case, just below the line)
Draw a line from the second Integrator and label it "r".
Insert an Out block from the Connections block library and connect it to the "r"
signal line. This will form the output of the system.
Change the label of the Out block to "r" by single-clicking on the existing "Out"
label.

Now, we will insert the function which takes the vector [r d/dt(r) alpha d/dt(alpha)] and
returns d/dt(r).

Insert a Fcn block from the Nonlinear library and connect its output to the input of
the first Integrator.
Edit the Fcn block by double clicking it, and change it's function to the following:

(-1/(J/(R^2)+m))*(m*g*sin(u[3])-m*u[1]*(u[4])^2)

This function block takes an input vector, u, where each component is referred to
as u[1], u[2], etc. In our case, u[1]=r, u[2]=d/dt(r), u[3]=alpha, and
u[4]=d/dt(alpha).

Close the dialog box and change the label of the Fcn block to "Ball-Beam
Lagrangian Model" (you can add newlines in the label by hitting return).

Now, we will begin to construct the function input vector u by feeding back the state
signals from the integrators and forming a vector from them with a Mux block.
Insert a Mux block from the Connections block library and connect its output to
the input of the Ball-Beam block.
Edit the Mux block (by double-clicking on it) and change its number of inputs to
4. The Mux block should now have four inputs.
Tap a line off the d/dt(r) signal (hold Ctrl while drawing) and connect it to the
second input of the Mux block.
Tap a line of the r signal and connect it to the first input of the Mux block.

Now we will construct the signals alpha and d/dt(alpha) from the input theta.
Insert an In block on the left side of your model window. Change its label to
"theta".
Insert a Gain block and connect it to the theta block. Change its gain value
(double-click on it) to "d/L".
Connect the output of the gain block to the third input of the Mux block. Label
this line "alpha".
Insert a Derivative block from the Linear block library and place it underneath the
alpha signal line.
Tap a line off the output of the Gain block and connect it to the input of the
Derivative block.
Connect the output of the Derivative block to the fourth input off the Mux block.

Save your model as "ball.mdl". You can download ours here. Open Loop Response To
generate the open-loop response, it is first necessary to contain this model in a subsystem
block.
Create a new model window (select New from the File menu in Simulink or hit
Ctrl-N).
Insert a Subsystem block from the Connections block library.
Open the Subsystem block by double clicking on it. You will see a new model
window labeled "Subsystem".
Open your previous model window named ball.mdl. Select all of the model
components by selecting Select All from the Edit menu (or hit Ctrl-A).
Copy the model into the paste buffer by selecting Copy from the Edit menu (or hit
Ctrl-C).
Paste the model into the Subsystem window by selecting Paste from the Edit
menu (or hit Ctrl-V) in the Subsystem window

Close the Subsystem window. You will see the Subsystem block in the untitled
window with one input terminal labeled theta and one output terminal labeled r.
Resize the Subsystem block to make the labels visible by selecting it and dragging
one of the corners.
Label the Subsystem block "Ball and Beam Model".

Insert a Step block (from the Sources block library) and connect it to the input of
the Ball and Beam Model.
Edit the Step block (by double clicking on it to bring up the dialog box) and
change the Step Time value to 0. Close the Step block dialog box.
Insert a Scope block (from the Sinks block library) and connect it to the output of
the Ball and Beam Model.

Before obtaining a step response, we must set the physical parameters Enter the following
commands at the MATLAB prompt.
m
R
g
L
d
J

=
=
=
=
=
=

0.111;
0.015;
-9.8;
1.0;
0.03;
9.99e-6;

We are now ready to run the simulation. If you like, you can download our version of the
open-loop system here. Start the simulation by selecting Start from the Simulation menu
(or hit Ctrl-t). When the simulation is finished, open the Scope by double clicking on it
and hit the Scope's autoscale button. You will see the following response.

From this plot it is clear that the system is unstable in open-loop causing the ball to roll
right off the end of the beam. Therefore, some method of controlling the ball's position in
this system is required. Later in this tutorial, we will implement a lead compensator.

Extracting the Model into MATLAB


The Simulink model can be extracted into an equivalent state-space or transfer function
model in MATLAB. This is done through the use of In and Out Connection blocks and the
MATLAB function linmod.
To extract a model, it is necessary to start with a model file with inputs and outputs
defined as In and Out blocks. Earlier in this tutorial this was done, and the file was saved
as ball.mdl. In this model, one input, theta (the input crank angle) and one output, r (ball
position), were defined.
At the MATLAB prompt, enter the following commands
[A,B,C,D]=linmod('ball')
[num,den]=ss2tf(A,B,C,D)

You will see the following output providing the open-loop model of the system.
A =

0
0

1
0

B =
0
0.2100
C =
1

D =
0
num =
0

0.2100

den =
1

We can verify this model by obtaining an open-loop step response. Enter the following
command at the MATLAB prompt:
step(num,den);

You will see the following open-loop response:

Building a Lead Compensator Controller


In the CTMS Example: Solution to the Ball & Beam Problem Using Root Locus Method
a lead compensator was designed with a zero at -0.01 and a pole at -5, with a gain of
37.1. We will now construct this controller in Simulink.
Bring up your open-loop Ball and Beam model window (or download ours here)
Delete the line which connects the Step block to the Ball and Beam model block.
Insert a Transfer Function block from the linear block library to the left of the Ball
and Beam block, and connect its output to the input of the Ball and Beam block.

Edit the Transfer Function block and change its numerator to "[1 0.01]" and its
denominator to "[1 5]".
Change the label of the Transfer Function block to "Lead Compensator".
Insert a Gain block to the left of the Lead Compensator and connect its output to
the Lead compensator's input.
Change the Gain value to "37.1".
Insert a Sum block to the left of the Gain block and change it's value to "+-".
Connect the output of the Sum to the input of the Gain block.
Tap a line off the output of the Ball and Beam model and connect it to the
negative input of the Sum.
Connect the Step block to the positive input of the Sum block

You can download our version of the closed-loop model here.

Closed-Loop Response
Start the simulation in Simulink. Open the scope window and hit the Autoscale button.
You should see the following response.

Example: Modeling the Ball and Beam


Experiment
Problem Setup
System Equations
MATLAB Representation and Open-Loop Response

Problem Setup
A ball is placed on a beam, see figure below, where it is allowed to roll with 1 degree of
freedom along the length of the beam. A lever arm is attached to the beam at one end and
a servo gear at the other. As the servo gear turns by an angle theta, the lever changes the
angle of the beam by alpha. When the angle is changed from the horizontal position,
gravity causes the ball to roll along the beam. A controller will be designed for this
system so that the ball's position can be manipulated.

For this problem, we will assume that the ball rolls without slipping and friction between
the beam and ball is negligible. The constants and variab for this example are defined as
follows:
M
R
d
g
L

mass of the ball


0.11 kg
radius of the ball
0.015 m
lever arm offset
0.03 m
gravitational acceleration 9.8 m/s^2
length of the beam
1.0 m

J
r
alpha
theta

ball's moment of inertia 9.99e-6 kgm^2


ball position coordinate
beam angle coordinate
servo gear angle

The design criteria for this problem are:

Settling time less than 3 seconds


Overshoot less than 5%

System Equations
The second derivative of the input angle alpha actually affects the second derivative of r.
However, we will ignore this contribution. The Lagrangian equation of motion for the
ball is then given by the following:

Linearization of this equation about the beam angle, alpha = 0, gives us the following
linear approximation of the system:

The equation which relates the beam angle to the angle of the gear can be approximated
as linear by the equation below:

Substituting this into the previous equation, we get:

1. Transfer Function
Taking the Laplace transform of the equation above, the following equation is found:

Rearranging we find the transfer function from the gear angle (theta(s)) to the ball
position (R(s)).

It should be noted that the above plant transfer function is a double integrator. As such it
is marginally stable and will provide a challenging control problem.

2. State-Space
The linearized system equations can also be represented in state-space form. This can be
done by selecting the ball's position (r) and velocity (rdot) as the state variab and the gear
angle (theta) as the input. The state-space representation is shown below:

However, for our state-space example we will be using a slightly different model. The
same equation for the ball still applies but instead of controlling the position through the
gear angle, theta, we will control the torque of the beam. Below is the representation of
this system:

Note: For this system the gear and lever arm would not be used, instead a motor at the
center of the beam will apply torque to the beam, to control the ball's position.

MATLAB Representation and Open-Loop Response


1. Transfer Function
The transfer function found from the Laplace transform can be implemented in MATLAB
by inputting the numerator and denominator as vectors. To do this we must create an mfile and copy the following text into it:
m
R
g
L
d
J

=
=
=
=
=
=

0.111;
0.015;
-9.8;
1.0;
0.03;
9.99e-6;

K = (m*g*d)/(L*(J/R^2+m));
num = [-K];
den = [1 0 0];
ball=tf(num,den)

Your output should be:


Transfer function:
0.21
---s^2

%simplifies input

Now, we would like to observe the ball's response to a step input of 0.25 m. To do this
you will need to add the following line to your m-file:
step(0.25*ball)
You should see the following plot showing the balls position as a function of time:

From this plot it is clear that the system is unstable in open-loop causing the ball to roll
right off the end of the beam. Therefore, some method of controlling the ball's position in
this system is required. Three examples of controller design are listed below for the
transfer function problem. You may select from PID, Root Locus, and Frequency
Response.

2. State-Space
The state-space equations can be represented in MATLAB with the following commands
(these equations are for the torque control model).
m
R
g
J

=
=
=
=

0.111;
0.015;
-9.8;
9.99e-6;

H = -m*g/(J/(R^2)+m);
A=[0 1 0 0
0 0 H 0
0 0 0 1
0 0 0 0];
B=[0;0;0;1];
C=[1 0 0 0];
D=[0];
ball=ss(A,B,C,D);

The step response to a 0.25m desired position can be viewed by running the command
below:
step(0.25*ball)
Your output should look like the following:

Like the plot for the transfer function this plot shows that the system is unstable and the
ball will roll right off the end of the beam. Therefore, we will require some method of
controlling the ball's position in this system. The State-Space example below shows how
to implement a controller for this type of system.
If you are interested in knowing how to convert state-space representations to transfer
function representations, and vice versa, see Conversions.

Example: Solution to the Ball & Beam


Problem Using PID Control
Closed-loop Representation
Proportional Control
Proportional-Derivative Control
The open-loop transfer function of the plant for the ball and beam experiment is given
below:

The design criteria for this problem are:

Settling time less than 3 seconds


Overshoot less than 5%

To see the derivation of the equations for this problem refer to the ball and beam
modeling page.

Closed-loop Representation
The block diagram for this example with a controller and unity feedback of the ball's
position is shown below:

First, we will study the response of the system shown above when a proportional
controller is used. Then, derivative and/or integral control will be added if necessary.
Recall, that the transfer function for a PID controller is:

Proportional Control
The closed-loop transfer function for proportional control with a proportional gain (kp)
equal to 100, can be modeled by copying the following lines of MATLAB code into an mfile (or a '.m' file located in the same directory as MATLAB)
m
R
g
L
d
J

=
=
=
=
=
=

0.111;
0.015;
-9.8;
1.0;
0.03;
9.99e-6;

K = (m*g*d)/(L*(J/R^2+m));

%simplifies input

num = [-K];
den = [1 0 0];
ball=tf(num,den);
kp = 1;
sys_cl=feedback(kp*ball,1);

Now, we can model the system's response to a step input of 0.25 m. Add the following
line of code to your m-file and run it:
step(0.25*sys_cl)
You should get the following output:

As, you can see the addition of proportional gain does not make the system stable. Try
changing the value of kp and note that the system remains unstable.

Proportional-Derivative Control
Now, we will add a derivative term to the controller. Copy the following lines of code to
an m-file and run it to view the system's response to this control method.
m
R
g
L
d
J

=
=
=
=
=
=

0.111;
0.015;
-9.8;
1.0;
0.03;
9.99e-6;

K = (m*g*d)/(L*(J/R^2+m));

%simplifies input

num = [-K];
den = [1 0 0];
ball=tf(num,den);
kp = 10;
kd = 10;
contr=tf([kd kp],1);
sys_cl=feedback(contr*ball,1);
t=0:0.01:5;
step(0.25*sys_cl)

Your plot should be similar to the following:

Now the system is stable but the overshoot is much too high and the settling time needs
to go down a bit. From the PID tutorial page in the section on characteristics of P, I, and
D controllers, we see that by increasing kd we can lower the overshoot and decrease the
settling time slightly. Therefore, make kd = 20 in your m-file and run it again. Your
output should be:

The overshoot criterion is met but the settling time needs to come down a bit. To decrease
the settling time we may try increasing the kp slightly to increase the rise time. The
derivative gain (kd) can also be increased to take off some of the overshoot that
increasing kp will cause. After playing with the gains a bit, the following step response
plot can be achieved with kp = 15 and kd = 40:

As you can see from the above plot all the control objectives have been met without the
use of an integral controller (settling time for this example is considered achieved when

the response is less than 2% of its final value). Remember, that for a control problem
there is usually more than one solution for the problem.
For other methods of controlling the ball and beam example, see the links below.

Example: Solution to the Ball & Beam


Problem Using Root Locus Method
Open-loop Root Locus
Lead Controller
Selecting a Gain
Plotting the Closed-loop Response
The open-loop transfer function of the plant for the ball and beam experiment is given
below:

The design criteria for this problem are:

Settling time less than 3 seconds


Overshoot less than 5%

To see the derivation of the equations for this problem refer to the ball and beam
modeling page. A schematic of the closed loop system with a controller is given below:

Open-loop Root Locus


The main idea of the root locus design is to estimate the closed-loop response from the
open-loop root locus plot. By adding zeroes and/or poles to the original system (adding a
compensator), the root locus and thus the closed-loop response will be modified. Let us

first view the root locus for the plant in open loop. Create an m-file with the following
MATLAB code in order to model the plant and plot the root locus.
m
R
g
L
d
J

=
=
=
=
=
=

0.111;
0.015;
-9.8;
1.0;
0.03;
9.99e-6;

K = (m*g*d)/(L*(J/R^2+m));

%simplifies input

num = [-K];
den = [1 0 0];
plant=tf(num,den);

rlocus(plant)
Now, run the m-file and you should see the following root locus plot:

As you can see the system has two poles at the origin which go off to infinity along the
imaginary axes.
The design criteria can also be plotted onto the root locus using the sgrid command.
This command generates a grid of constant damping ratio and natural frequency. The
damping ratio and natural frequency were found using the following equation, which
relates the them to our percent overshoot (PO) and settling time (Ts) requirements:

Note, that the equation with Ts is found by assuming the system has settled is when the
response remains within 2% of its final value. From these equations, the damping ratio
and natural frequency were found to be 0.7 and 1.9 respectively.
sgrid(0.70, 1.9)
axis([-5 5 -2 2])

The area between the two dotted diagonal lines represents locations where the percent
overshoot is less than 5%. The area outside the curved line represents locations where the
settling time is less than 3 seconds. Note that no region of the plot falls within the design
criteria shown be these lines. To remedy this and bring the root locus into the left-hand
plane for stability we will try adding a lead-compensator to the system.

Lead Controller
A first order lead compensator tends to shift the root locus into the left-hand plane. For a
more detailed description of lead compensators refer to the Lead & Lag Compensator
Design page. A lead compensator has the form given below:

where, the magnitude of zo is less than the magnitude of po.

Now, let us add the controller to the plant and view the root locus. We will position the
zero near the origin to cancel out one of the poles. The pole of our compensator will be
placed to the left of the origin to pull the root locus further into the left-hand plane. Add
the following lines of MATLAB code to your m-file.
zo = 0.01;
po = 5;
contr=tf([1 zo],[1 po]);

rlocus(contr*plant)
sgrid(0.70, 1.9)
Run your m-file in the MATLAB command window and you should see the following:

Now, the branches of the root locus are within our design criteria.

Selecting a Gain
Now that we have moved the root locus into the left-hand plane, we may select a gain
that will satisfy our design requirements. We can use the rlocfind command to help us
do this. Add the following onto the end of your m-file.
[k,poles]=rlocfind(contr*plant)
Go to the plot and select a point near those indicated by the cross mark on the plot below:

You should see in the MATLAB command window something similar to the following
(your numbers may be slightly different):
selected_point =
-2.4988+ 1.2493i
k =
37.3131
poles =
-2.4950+ 1.2493i
-2.4950- 1.2493i
-0.0101

Now, we can plot the response with this gain.

Plotting the Closed-loop Response


This value of kc can be put into the system and the closed-loop response to a step input of
0.25 m can be obtained. Add the following lines to your m-file to perform this analysis.
sys_cl=feedback(k*contr*plant,1);
t=0:0.01:5;
figure
step(sys_cl,t)

Run your m-file and select a point on the root locus similar to the selected point above.
The step response should look like the following:

From this plot we see that when a 0.25m step input is given to the system both the
settling time and percent overshoot design criteria are met.
Note: A design problem does not necessarily have a unique answer. Using this method (or
any other) may result in many different compensators. Try running your m-file several
more times selecting a different point each time and study the effect this has on the step
response. For practice you may also want to go back to the original open-loop root locus
and try to find other ways to add zeros and poles to get a better response.

Example: Solution to the Ball & Beam


Problem Using Frequency Response Method
Open-loop Bode Plot
Phase-Lead Controller
Adding More Phase
The open-loop transfer function of the plant for the ball and beam example is given
below:

The design criteria for this problem are:

Settling time less than 3 seconds


Overshoot less than 5%

To see the derivation of the equations for this problem refer to the ball and beam
modeling page. A schematic of the closed loop system with a controller is given below:

Open-loop Bode Plot


The main idea of frequency based design is to use the Bode plot of the open-loop transfer
function to estimate the closed-loop response. Adding a controller to the system changes
the open-loop Bode plot, therefore changing the closed-loop response. Let's first draw the
bode plot for the original open-loop transfer function. Create an m-file with the following
code and then run it in the MATLAB command window:
m
R
g
L
d
J

=
=
=
=
=
=

0.111;
0.015;
-9.8;
1.0;
0.03;
9.99e-6;

K = (m*g*d)/(L*(J/R^2+m));
num = [-K];
den = [1 0 0];
ball=tf(num,den);

bode(ball)
You should get the following Bode plot:

%simplifies input

From this plot we see that the phase margin is zero. Since the phase margin is defined as
the change in open-loop phase shift necessary to make a closed-loop system unstable this
means that our zero phase margin indicates our system is unstable. We want to increase
the phase margin and we can use a lead compensator controller to do this. For more
information on Phase and Gain margins please refer to the Frequency Response Tutorial.

Phase-Lead Controller
A first order phase-lead compensator has the form given below:

The phase-lead compensator will add positive phase to our system over the frequency
range 1/aT and 1/T, which are called the corner frequencies. The maximum added phase
for one lead compensator is 90 degrees. For our controller design we need a percent
overshoot of less than 5 %, which corresponds to a zeta of 0.7. Generally zeta * 100 will
give you the minimum phase margin needed to obtain your desired overshoot. Therefore
we require a phase margin greater than 70 degrees.
To obtain "T" and "a", the following steps can be used.
1. Determine the positive phase needed:
We need at least 70 degrees from our controller.
2. Determine the frequency where the phase should be added (center frequency):

In our case this is difficult to determine because the phase vs. frequency graph in
the bode plot is a flat line. However, we have a relation between bandwidth
frequency (wbw) and settling time (refer to the Bandwidth Frequency page for
this equation) which tells us that wbw is approximately 1.92 rad/s. Therefore we
want a center frequency just before this. For now we will choose 1.
3. Determine the constant "a" from the equation below, this determines the required
space between the zero and the pole for the maximum phase added.

where phi refers to the desired phase margin. For 70 degrees, a = 0.0311.
4. Determine "T" and "aT" from the following equations:

For 70 degrees and center frequency (w) = 1, aT = 0.176 and T = 5.67


Now, we can add our lead controller to the system and view the bode plot. Remove the
bode command from your m-file and add the following:
phi=70*pi/180;
a=(1-sin(phi))/(1+sin(phi));
w=1;
T=1/(w*sqrt(a));
k = 1;
numlead = k*[T 1];
denlead = [a*T 1];
contr = tf(numlead,denlead);

bode(contr*ball)
You should get the following bode plot:

You can see that our phase margin is now 70 degrees. Let's check the closed-loop
response to a step input of 0.25m. Add the following to your m-file:
sys_cl = feedback(contr*ball,1);
t = 0:0.01:5;
step(0.25*sys_cl,t)

You should get the following plot:

Although the system is now stable and the overshoot is only slightly over 5%, the settling
time is not satisfactory. Increasing the gain will increase the crossover frequency and
make the response faster. With k = 5, your response should look like:

The response is faster, however, the overshoot is much too high. Increasing the gain
further will just make the overshoot worse.

Adding More Phase


We can increase our phase-lead compensator to decrease the overshoot. In order to make
the iterative process easier use the following program. Create an m-file and copy the
function from your web-browser into it (make sure the function command starts in the
first column of the m-file).
function[ ] = phaseball()

%define TF
m = 0.111;
R = 0.015;
g = -9.8;
L = 1.0;
d = 0.03;
J = 9.99e-6;
K = (m*g*d)/(L*(J/R^2+m));

%simplifies input

num = [-K];
den = [1 0 0];
ball = tf(num,den);
%ask
pm =
w =
k =

user for controller information


input('Phase Margin?.......');
input('Center Frequency?...');
input('Gain?...............');

%view compensated system bode plot


pmr = pm*pi/180;
a = (1 - sin(pmr))/(1+sin(pmr));
T = sqrt(a)/w;
aT = 1/(w*sqrt(a));
numlead = k*[aT 1];
denlead = [T 1];
contr = tf(numlead,denlead);
figure
bode(contr*ball)
%view step response
sys_cl = feedback(contr*ball,1);
t = 0:0.01:5;
figure
step(0.25*sys_cl,t)

With this m-file you can choose the phase margin, center frequency, and gain. Run your
m-file with the following values and you should see the plots below on your screen.
Phase Margin?.......80
Center Frequency?...1
Gain?...............1

The overshoot is fine but the settling time is just a bit long. Try different numbers and see
what happens.
Using the following values the design criteria was met.
Phase Margin?.......85
Center Frequency?...1.9
Gain?...............2

Note: A design problem does not necessarily have a unique answer. Using this method (or
any other) may result in many different compensators. For practice you may want to go
back and change the added phase, gain, or center frequency.

Example: Solution to the Ball & Beam


Problem Using the State-space Design
Method

Full-State Feedback Controller


Reference Input
The state-space representation of the ball and beam example is given below:

Unlike the previous examples where we controlled the gear's angle to control the beam
and ball, here we are controlling alpha-doubledot. By doing this we are essentially
controlling a torque applied at the center of the beam by a motor. Therefore, we do not
need a gear and lever system.
The design criteria for this problem are:

Settling time less than 3 seconds


Overshoot less than 5%

To see the derivation of the state-space equations for this problem refer to the ball and
beam modeling page.
If you are interested in running an animation of this example based on the control
techniques used in the state-space tutorial please go to the Ball & Beam Animation Page
after completing this tutorial.

Full-State Feedback Controller


We will design a controller for this physical system that utilizes full-state feedback
control. A schematic of this type of system is shown below:

Recall, that the characteristic polynomial for this closed-loop system is the determinant of
(sI-(A-BK)), where s is the Laplace variable. For our system the A and B*K matrices are
both 4x4. Hence, there should be four poles for our system. In designing our full-state
feedback controller we can move these poles anywhere we want.
For our design we desire an overshoot of less than 5% which corresponds to a zeta of 0.7
(please refer to your textbook for the relationship between overshoot and damping ratio).
On a root locus this criterion is represented as a 45 degree line emanating from the origin
and extending out into the left-half plane. We want to place our desired poles on or
beneath this line. Our next criterion is a settling time less than 3 seconds, which
corresponds to a sigma = 4.6/Ts = 4.6/3 = 1.53, represented by a vertical line at -1.53 on
the root locus. Anything beyond this line in the left-half plane is a suitable place for our
poles. Therefore we will place our poles at -2+2i and -2-2i. We will place the other poles
far to the left for now, so that they will not affect the response too much. To start with
place them at -20 and -80. Now that we have our poles we can use MATLAB to find the
controller (K matrix) by using the place command. Copy the following code to an m-file
to model the system and find the K matrix:
m
R
g
J

=
=
=
=

0.111;
0.015;
-9.8;
9.99e-6;

H = -m*g/(J/(R^2)+m);
A = [0 1 0 0
0 0 H 0
0 0 0 1
0 0 0 0];
B = [0;0;0;1];
C = [1 0 0 0];
D = [0];
ball = ss(A,B,C,D);
p1 = -2+2i;
p2 = -2-2i;
p3 = -20;

p4 = -80;
K = place(A,B,[p1,p2,p3,p4])
Run your m-file and you should get the following output for the K matrix:
place: ndigits= 15
K =
1.0e+03 *
1.8286

1.0286

2.0080

0.1040

After adding the K matrix, the state space equations now become:

We can now simulate the closed-loop response to a 0.25m step input by using the lsim
command. Add the following to your m-file:
T = 0:0.01:5;
U = 0.25*ones(size(T));
sys_cl = ss(A-B*K,B,C,D);
[Y,T,X] = lsim(sys_cl,U,T);
plot(T,Y)

Run your m-file and you should get the following plot:

From this plot we see that there is a large steady state error, to compensate for this, we
will need to add a reference input compensation (explained in next section). However, the
overshoot and settling time criteria are met. If we wanted to reduce the overshoot further,
we could make the imaginary part of the pole smaller than the real part. Also, if we

wanted a faster settling time we would move the poles further in the left-half plane. Feel
free to experiment with the pole positions to see these trends.

Reference Input
Now we want to get rid of the steady-state error. In contrast to the other design methods,
where we feedback the output and compare it to the reference input to compute an error,
with a full-state feedback controller we are feeding back both states. We need to compute
what the steady-state value of the states should be, multiply that by the chosen gain K,
and use a new value as our reference for computing the input. This can be done by adding
a constant gain Nbar after the reference. The schematic below shows this relationship:

Nbar can be found using the user-defined function rscale (copy it to the directory that
your m-file is in). Copy the following to your m-file and run it to view the step response
with Nbar added.
Nbar=rscale(ball,K)
T = 0:0.01:5;
U = 0.25*ones(size(T));
[Y,T,X]=lsim(Nbar*sys_cl,U,T);
plot(T,Y)

Your output should be:


place: ndigits= 15
Nbar =
1.8286e+03

Now the steady-state error has been eliminated and all the design criteria are satisfied.
Note: A design problem does not necessarily have a unique answer. Using this method (or
any other) may result in many different compensators. For practice you may want to go
back and try to change the pole positions to see how the system responds.
If you are interested in running an animation of the ball & beam example based on the
control techniques used in this tutorial please go to the Ball & Beam Animation Page.

Digital Control Example: Ball and Beam


problem using PID Control
Digital PID controller
Discrete transfer function
Open-loop response
Proportional control
Proportional-Derivative control
In this digital control version of the ball and beam experiment, we are going to use the
PID control method to design the digital controller. If you refer to the Ball and Beam
Modeling page, the open-loop transfer function was derived as

m
g
d
L
R
J
R(s)
theta(s)

mass of the ball


0.11 kg
gravitational acceleration 9.8 m/s^2
lever arm offset
0.03 m
length of the beam
1.0 m
radius of the ball
0.015 m
ball's moment of inertia
9.99e-6 kgm^2
ball position coordinate (m)
servo gear angle
0.25 rad

The design criteria for this problem are:

Settling time less than 3 seconds


Overshoot less than 5%

Digital PID controller


If you refer to any of the PID control problem for continuous systems, the PID transfer
function was expressed as

As you noticed the above transfer function was written in terms of s. For the digital PID
control, we use the following transfer function in terms of z.

Discrete transfer function


The first thing to do here is to convert the above continuous system transfer function to
an equivalent discrete transfer function. To do this, we will use the MATLAB function c2d.
To use c2d, we need to specify three arguments: system, sampling time (Ts), and the
'method'. You should already be familiar with how to create a system from numerator and
denominator matrices. The sampling time should be smaller than 1/(30*BW) sec, where
BW is the closed-loop bandwidth frequency. The method we will use is the zero-order
hold ('zoh'). Assuming that the closed-loop bandwidth frequency is around 1 rad/sec, let

the sampling time be 1/50 sec/sample. Now we are ready to use c2d. Enter the following
commands to an m-file.
m
R
g
L
d
J

=
=
=
=
=
=

0.111;
0.015;
-9.8;
1.0;
0.03;
9.99e-6;

K = (m*g*d)/(L*(J/R^2+m));

%simplifies input

num = [-K];
den = [1 0 0];
ball = tf(num,den);
Ts = 1/50;
ball_d = c2d(ball,Ts,'zoh')

Running this m-file in the MATLAB command window gives you the following matrices.
Transfer function:
4.2e-05 z + 4.2e-05
------------------z^2 - 2 z + 1
Sampling time: 0.02

Open-loop response
Now we will observe the ball's response to a step input of 0.25 m. To do this, enter the
following commands into a new m-file and run it in the command window. You should
see the following response.
numDz = 0.0001*[0.42 0.42];
denDz = [1 -2 1];
Ts = 1/50;
ball_d = tf(numDz,denDz,Ts);
[x,t] = step(0.25*ball_d,5);
stairs(t,x)

From this plot, it is clear that the open-loop system is unstable causing the ball to roll off
the end of the beam.

Proportional Control

Now we will add proportional control (Kp) to the system and obtain the closed-loop
system response. For now let Kp equal 100 and see what happens to the response. Enter
the following commands into a new m-file and run it in the command window.
numDz = 0.0001*[0.42 0.42];
denDz = [1 -2 1];
Ts = 1/50;
ball_d = tf(numDz,denDz,Ts);
Kp=100;
sys_cl =

feedback(Kp*ball_d,1);

[x,t] = step(0.25*sys_cl,5);
stairs(t,x)

As you can see, the addition of proportional control does not make the system stable. You
may try to increase the proportional gain (Kp) and confirm that the system remains
unstable.

Proportional-Derivative control
Now we will add a derivative term to the controller. Keep the proportional gain (Kp)
equal to 100, and let the derivative gain (Kd) equal to 10. Copy the following code to an
new m-file and run it to view the system response.
numDz = 0.0001*[0.42 0.42];
denDz = [1 -2 1];
Ts = 1/50;
ball_d = tf(numDz,denDz,Ts);
Kp=100;
Kd=10;
numpd = [Kp+Kd -(Kp+2*Kd) Kd];
denpd = [1 1 0];
contr = tf(numpd,denpd,Ts);

sys_cl =

feedback(contr*ball_d,1);

[x,t] = step(0.25*sys_cl,5);
stairs(t,x)

Now the system is stable, but the rise time is too long. From the PID Tutorial page, we
see that the increasing the proportional gain (Kp) will decrease the rise time. Let's
increase the proportional gain (Kp) to 1000 and see what happens. Change Kp in the
above m-file from 100 to 1000 and rerun it in the command window. You should see the
following step response.

As you can see, all of the design requirements are satisfied. For this particular problem,
no implementation of an integral control was needed. But remember there is more than
one solution for a control problem. For practice, you may try different P, I and D
combinations to obtain a satisfactory response.

Example: Modeling the Ball and Beam


Experiment in Simulink
Problem Setup and System Equations
Building the Simulink Model
Open-Loop Response
Extracting the Model into MATLAB
Constructing a Lead Compensator Controller
Closed-Loop Response

Problem Setup
A ball is placed on a beam, see figure below, where it is allowed to roll with 1 degree of
freedom along the length of the beam. A lever arm is attached to the beam at one end and
a servo gear at the other. As the servo gear turns by an angle theta, the lever changes the
angle of the beam by alpha. When the angle is changed from the horizontal position,
gravity causes the ball to roll along the beam. A controller will be designed for this
system so that the ball's position can be manipulated.

For this problem, we will assume that the ball rolls without slipping and friction between
the beam and ball is negligible. The constants and variab for this example are defined as
follows:
M
R
d
g
L
J
r
alpha
theta

mass of the ball


0.11 kg
radius of the ball
0.015 m
lever arm offset
0.03 m
gravitational acceleration 9.8 m/s^2
length of the beam
1.0 m
ball's moment of inertia 9.99e-6 kgm^2
ball position coordinate
beam angle coordinate
servo gear angle

The design criteria for this problem are:

Settling time less than 3 seconds


Overshoot less than 5%

The second derivative of the input angle alpha actually affects the second derivative of r.
However, we will ignore this contribution. The Lagrangian equation of motion for the
ball is then given by the following:

The beam angle (alpha) can be expressed in terms of the angle of the gear (theta).

Building the Model in Simulink


In this example, rather than express all the forces and geometric constraints (which is
difficult to model in Simulink for dynamic systems with constraints) we will model the
nonlinear Lagrangian equation of motion directly. This equation gives d/dt(r) as a
function of the state and input variab, r, d/dt(r), alpha, and d/dt(alpha). We will make use
of the Nonlinear Function Block to express this function. First, we must express the
derivatives of the output, r.
Open a new model window in Simulink.
Insert an Integrator block from the Linear block library.
Insert a second Integrator to the right of the first, and connect the two with a line.
Label the line connecting the two "d/dt(r)". To label a line, double-click near the
line where you want the label (in this case, just below the line)
Draw a line from the second Integrator and label it "r".
Insert an Out block from the Connections block library and connect it to the "r"
signal line. This will form the output of the system.
Change the label of the Out block to "r" by single-clicking on the existing "Out"
label.

Now, we will insert the function which takes the vector [r d/dt(r) alpha d/dt(alpha)] and
returns d/dt(r).

Insert a Fcn block from the Nonlinear library and connect its output to the input of
the first Integrator.
Edit the Fcn block by double clicking it, and change it's function to the following:

(-1/(J/(R^2)+m))*(m*g*sin(u[3])-m*u[1]*(u[4])^2)

This function block takes an input vector, u, where each component is referred to
as u[1], u[2], etc. In our case, u[1]=r, u[2]=d/dt(r), u[3]=alpha, and
u[4]=d/dt(alpha).

Close the dialog box and change the label of the Fcn block to "Ball-Beam
Lagrangian Model" (you can add newlines in the label by hitting return).

Now, we will begin to construct the function input vector u by feeding back the state
signals from the integrators and forming a vector from them with a Mux block.
Insert a Mux block from the Connections block library and connect its output to
the input of the Ball-Beam block.
Edit the Mux block (by double-clicking on it) and change its number of inputs to
4. The Mux block should now have four inputs.
Tap a line off the d/dt(r) signal (hold Ctrl while drawing) and connect it to the
second input of the Mux block.
Tap a line of the r signal and connect it to the first input of the Mux block.

Now we will construct the signals alpha and d/dt(alpha) from the input theta.
Insert an In block on the left side of your model window. Change its label to
"theta".
Insert a Gain block and connect it to the theta block. Change its gain value
(double-click on it) to "d/L".
Connect the output of the gain block to the third input of the Mux block. Label
this line "alpha".
Insert a Derivative block from the Linear block library and place it underneath the
alpha signal line.
Tap a line off the output of the Gain block and connect it to the input of the
Derivative block.
Connect the output of the Derivative block to the fourth input off the Mux block.

Save your model as "ball.mdl". You can download ours here. Open Loop Response To
generate the open-loop response, it is first necessary to contain this model in a subsystem
block.
Create a new model window (select New from the File menu in Simulink or hit
Ctrl-N).
Insert a Subsystem block from the Connections block library.
Open the Subsystem block by double clicking on it. You will see a new model
window labeled "Subsystem".
Open your previous model window named ball.mdl. Select all of the model
components by selecting Select All from the Edit menu (or hit Ctrl-A).
Copy the model into the paste buffer by selecting Copy from the Edit menu (or hit
Ctrl-C).
Paste the model into the Subsystem window by selecting Paste from the Edit
menu (or hit Ctrl-V) in the Subsystem window

Close the Subsystem window. You will see the Subsystem block in the untitled
window with one input terminal labeled theta and one output terminal labeled r.
Resize the Subsystem block to make the labels visible by selecting it and dragging
one of the corners.
Label the Subsystem block "Ball and Beam Model".

Insert a Step block (from the Sources block library) and connect it to the input of
the Ball and Beam Model.
Edit the Step block (by double clicking on it to bring up the dialog box) and
change the Step Time value to 0. Close the Step block dialog box.
Insert a Scope block (from the Sinks block library) and connect it to the output of
the Ball and Beam Model.

Before obtaining a step response, we must set the physical parameters Enter the following
commands at the MATLAB prompt.
m
R
g
L
d
J

=
=
=
=
=
=

0.111;
0.015;
-9.8;
1.0;
0.03;
9.99e-6;

We are now ready to run the simulation. If you like, you can download our version of the
open-loop system here. Start the simulation by selecting Start from the Simulation menu
(or hit Ctrl-t). When the simulation is finished, open the Scope by double clicking on it
and hit the Scope's autoscale button. You will see the following response.

From this plot it is clear that the system is unstable in open-loop causing the ball to roll
right off the end of the beam. Therefore, some method of controlling the ball's position in
this system is required. Later in this tutorial, we will implement a lead compensator.

Extracting the Model into MATLAB


The Simulink model can be extracted into an equivalent state-space or transfer function
model in MATLAB. This is done through the use of In and Out Connection blocks and the
MATLAB function linmod.
To extract a model, it is necessary to start with a model file with inputs and outputs
defined as In and Out blocks. Earlier in this tutorial this was done, and the file was saved
as ball.mdl. In this model, one input, theta (the input crank angle) and one output, r (ball
position), were defined.
At the MATLAB prompt, enter the following commands
[A,B,C,D]=linmod('ball')
[num,den]=ss2tf(A,B,C,D)

You will see the following output providing the open-loop model of the system.
A =
0
0

1
0

B =
0
0.2100
C =
1

D =
0
num =
0

0.2100

den =
1

We can verify this model by obtaining an open-loop step response. Enter the following
command at the MATLAB prompt:
step(num,den);

You will see the following open-loop response:

Building a Lead Compensator Controller


In the CTMS Example: Solution to the Ball & Beam Problem Using Root Locus Method
a lead compensator was designed with a zero at -0.01 and a pole at -5, with a gain of
37.1. We will now construct this controller in Simulink.
Bring up your open-loop Ball and Beam model window (or download ours here)
Delete the line which connects the Step block to the Ball and Beam model block.
Insert a Transfer Function block from the linear block library to the left of the Ball
and Beam block, and connect its output to the input of the Ball and Beam block.

Edit the Transfer Function block and change its numerator to "[1 0.01]" and its
denominator to "[1 5]".
Change the label of the Transfer Function block to "Lead Compensator".
Insert a Gain block to the left of the Lead Compensator and connect its output to
the Lead compensator's input.
Change the Gain value to "37.1".
Insert a Sum block to the left of the Gain block and change it's value to "+-".
Connect the output of the Sum to the input of the Gain block.
Tap a line off the output of the Ball and Beam model and connect it to the
negative input of the Sum.
Connect the Step block to the positive input of the Sum block

You can download our version of the closed-loop model here.

Closed-Loop Response
Start the simulation in Simulink. Open the scope window and hit the Autoscale button.
You should see the following response.

Вам также может понравиться