Simulink Basics Tutorial - Interaction With MATLAB

advertisement
MATLAB Commands List
The following list of commands can be very useful for future reference. Use "help" in
MATLAB for more information on how to use the commands.
In these tutorials, we use commands both from MATLAB and from the Control Systems
Toolbox, as well as some commands/functions which we wrote ourselves. For those
commands/functions which are not standard in MATLAB, we give links to their descriptions.
For more information on writing MATLAB functions, see the function page.
Note: MATLAB commands from the control system toolbox are highlighted in red.
Non-standard MATLAB commands are highlighted in green.
Command
abs
Absolute value
Description
acker
Compute the K matrix to place the poles of A-BK, see also place
axis
Set the scale of the current plot, see also plot, figure
bode
Draw the Bode plot, see also logspace, margin, nyquist1
c2d
Continuous system to discrete system
clf
Clear figure
conv
Convolution (useful for multiplying polynomials), see also deconv
ctrb
The controllability matrix, see also obsv
deconv
Deconvolution and polynomial division, see also conv
det
Find the determinant of a matrix
dlqr
Linear-quadratic regulator design for discrete-time systems, see also lqr
eig
Compute the eigenvalues of a matrix
eps
MATLAB's numerical tolerance
feedback
Connect linear systems in a feedback loop
figure
Create a new figure or redefine the current figure, see also subplot, axis
for
For, next loop
format
Number format (significant digits, exponents)
function
Creates function m-files
grid
Draw the grid lines on the current plot
gtext
Add a piece of text to the current plot, see also text
help
HELP!
hold
Hold the current graph, see also figure
if
Conditionally execute statements
imag
Returns the imaginary part of a complex number, see also real
impulse
Impulse response of linear systems, see also step, lsim
input
Prompt for user input
inv
Find the inverse of a matrix
legend
Graph legend
length
Length of a vector, see also size
linspace
Returns a linearly spaced vector
lnyquist
Produce a Nyquist plot on a logarithmic scale, see also nyquist1
log
natural logarithm, also log10: common logarithm
loglog
Plot using log-log scale, also semilogx/semilogy
logspace
Returns a logarithmically spaced vector
lqr
Linear quadratic regulator design for continuous systems, see also dlqr
lsim
Simulate a linear system, see also step, impulse
margin
Returns the gain margin, phase margin, and crossover frequencies, see also bode
minreal
Produces a minimal realization of a system (forces pole/zero cancellations)
norm
Norm of a vector
nyquist1
Draw the Nyquist plot, see also lnyquist. Note this command was written to
replace the MATLAB standard command nyquist to get more accurate Nyquist
plots.
obsv
The observability matrix, see also ctrb
ones
Returns a vector or matrix of ones, see also zeros
place
Compute the K matrix to place the poles of A-BK, see also acker
plot
Draw a plot, see also figure, axis, subplot.
poly
Returns the characteristic polynomial
polyval
Polynomial evaluation
print
Print the current plot (to a printer or postscript file)
pzmap
Pole-zero map of linear systems
rank
Find the number of linearly independent rows or columns of a matrix
real
Returns the real part of a complex number, see also imag
rlocfind
Find the value of k and the poles at the selected point
rlocus
Draw the root locus
roots
Find the roots of a polynomial
rscale
Find the scale factor for a full-state feedback system
set
Set(gca,'Xtick',xticks,'Ytick',yticks) to control the number and spacing of tick
marks on the axes
sgrid
Generate grid lines of constant damping ratio (zeta) and natural frequency (Wn),
see also sigrid, zgrid
sigrid
Generate grid lines of constant settling time (sigma), see also sgrid, zgrid
size
Gives the dimension of a vector or matrix, see also length
sqrt
Square root
ss
Create state-space models or convert LTI model to state space, see also tf
ssdata
Access to state-space data. See also tfdata
stairs
Stairstep plot for discrete response
step
Plot the step response, see also impulse, lsim
subplot
Divide the plot window up into pieces, see also plot, figure
text
Add a piece of text to the current plot, see also title, xlabel, ylabel, gtext
tf
Creation of transfer functions or conversion to transfer function, see also ss
tfdata
Access to transfer function data, see also ssdata
title
Add a title to the current plot
wbw
Returns the bandwidth frequency given the damping ratio and the rise or settling
time.
xlabel/ylabel
Add a label to the horizontal/vertical axis of the current plot, see also title, text,
gtext
zeros
Returns a vector or matrix of zeros
zgrid
Generates grid lines of constant damping ratio (zeta) and natural frequency
(Wn), see also sgrid, sigrid
Simulink Basics Tutorial - Block Libraries
Sources
Sinks
Discrete
Linear
Nonlinear
Connections
Simulink contains a large number of blocks from which models can be built. These blocks are
arranged in Block Libraries which are accessed in the main Simulink window shown below
Each icon in the main Simulink window can be double clicked to bring up the corresponding
block library. Blocks in each library can then be dragged into a model window to build a
model.
Sources
Source Blocks are used to generate signals. Double-click on the Sources icon in the main
Simulink window to bring up the Sources window.
Notice that all of the source blocks have a single output and no inputs. While parameters in
each of these blocks in the library can be modified by double-clicking the block, it is best to
not modify the blocks until they have been copied into a model window.
In order to examine these blocks, create a new model window (select New from the File menu
in the Simulink window or hit Ctrl+N).
Constant
The Constant Source Block simply generates a constant signal. The constant output value is
displayed in the middle of the block, with a default value of 1.
To use this block, drag it from the Sources window into your new model window.
To change the constant output value, double-click on the block in your model window to
bring up the following dialog box.
Change the constant value field from 1 to some other value, say, 5, and close the dialog box.
Your model window will reflect the update by displaying a 5 in the middle of the constant
block.
Signal Generator
The Signal Generator Source Block is a general-purpose source which encompasses some of
the other blocks' functions. It generates periodic waveforms such as sine, square, and
sawtooth waves as well as a random signal. Drag this block from the Sources window to your
model window.
By default, the Signal Generator generates a sine wave with an amplitude of 1 and a
frequency of 1 Hz. To change this, double-click the Signal Generator in your model window
to bring up the following dialog box.
The Amplitude and Frequency can be changed in this dialog box, as well as the type of
waveform. To change the waveform, click on the Waveform field to bring up a list of possible
waveforms.
The desired waveform can be selected from this list.
Ramp
The Ramp Source Block generates a signal which is initially constant and begins to increase
(or decrease) at a constant rate at a specified time. The slope, start time, and initial output can
be specified.
Sine Wave
The Sine Wave Source Block generates a sinusoidal signal. The Amplitude and Frequency
can be specified, as well as the Phase (unlike the Signal Generator). There is a fourth
parameter, the Sample Time, which can be used to force the Sine Wave Source to operate in
discrete-time mode (more about Discrete Time systems in Simulink later.)
Step
As described earlier, the Step Source Block generates a step function. The initial and final
values can be specified, as well as the step time.
Chirp Signal
The Chirp Signal Source Block generates a sinusoidal signal which scans over a range of
frequencies. The initial and final frequencies as well as the scan time can be specified. The
amplitude is always 1, and the chirp signal repeats itself after each frequency scan.
Pulse Generator
The Pulse Generator Source Block generates a pulse train of varying duty cycle. The signal
switches between 0 and the specified value starting at a particular time. The Period, Duty
Cycle, Amplitude, and Start Time can be specified.
Repeating Sequence
An arbitrary set of points (t,y) can be specified. These points are entered as a vector
specifying the time values, and a vector specifying the corresponding output values at those
times. The output is linearly interpolated between the specified time values. At the last time
value, the output immediately starts over, possibly with a discontinuous transition.
Clock
The Clock Source Block generates a signal equal to the current time in the simulation. This is
useful when the output of a simulation is exported to MATLAB but occurs at uneven time
steps. The clock's output reflects the times at which the other signals outputs occur.
Digital Clock
The Digital Clock Source Block generates a strictly periodic time signal at a specified
sampling interval.
From File
The From File Source Block outputs a signal taken from a specified .mat file. A matrix saved
in MATLAB as a .mat file will become a signal where the first row of the matrix specifies the
time values. This is similar to the Repeating Sequence Source Block.
From Workspace
The From Workspace Source Block is identical to the From File Source Block except the
values are taken from a variable (or expression) in the MATLAB Workspace.
Random Number
The Random Number Source Block generates a sequence of random numbers generated with
the specified random number seed. Because of the seed, the same sequence can be applied to
more than one simulation.
Band-Limited White Noise
The Band-Limited White Noise Source Block generates a random signal which changes at a
specified sample period. The strength of the signal and a random number seed can also be
specified.
Sinks
Sink Blocks are used to display or output signals. Double-click on the Sinks icon in the main
Simulink window to bring up the Sinks window.
Notice that all of the sink blocks have inputs and no outputs. Most have a single input.
Scope
The Scope Sink Block was described earlier. It is used to display a signal as a function of
time.
XY Graph
The XY Graph Sink Block plots one signal against another. It is useful for phase-plane plots,
etc.
Display
The Display Sink Block is a digital readout of a signal at the current simulation time.
To File
The To File Sink Block saves a signal to a .mat file in the same way that the From File Source
Block reads from a file. The sampling time can be specified, but is not necessary.
To Workspace
The To Workspace Sink Block stores a signal in a specified workspace variable. Unlike the
To File Sink Block, the time is not saved in the variable, and must be stored separately.
Stop Simulation
This is a special control block which is triggered to stop the current simulation when its input
is non-zero.
Discrete
Discrete Blocks are elements of discrete time dynamic systems. Double-click on the Discrete
icon in the main Simulink window to bring up the Discrete window.
In order for these block to interact with continuous time blocks (sources and sinks, for
example) the sample time can be specified in all of the Discrete Blocks.
Unit Delay
The Unit Delay's output is equal to the input delayed by one sample time.
Discrete-Time Integrator
This is the discrete time approximation of a continuous-time integrator. The approximation
method can be specified as well as the initial condition and saturation limits.
Zero-Order Hold
Outputs a stepwise-constant version of the input signal with a specified sampling period.
First-Order Hold
Outputs a piecewise-linear version of the input signal with a specified sampling period.
Discrete State-Space
This is a discrete-time dynamic system in state-space form. A, B, C, and D matrices can be
specified, as well as initial conditions.
Discrete Filter
This is a discrete-time filter in rational function form. Vectors containing coefficients of the
polynomials in z^-1 are specified.
Discrete Transfer Fcn
This is the standard form of a SISO LTI discrete time system. The transfer function
polynomials are represented as coefficient vectors in terms of z.
Discrete Zero-Pole
A discrete-time transfer function can be represented as list of z-plane poles and zeros. The
gain can also be specified.
Linear
Linear Blocks are elements of linear continuous-time dynamic systems. Double-click on the
Linear icon in the main Simulink window to bring up the Linear window.
Gain
This is a scalar or vector gain. The specified gain multiplies the input. The output is either a
scalar or vector signal following normal vector-scalar multiplication rules.
Sum
The Sum Block adds (or subtracts) two (or more) signals and outputs their sum (or
difference). The two inputs must either all be scalars, or all be vectors of the same dimension.
The output is the same dimension as the inputs.
Drag this block into your model window and double click on it, bringing up the following
dialog box.
By default, the Sum block adds two signals. The list of signs field represents both the number
of inputs and whether to add or subtract them. To make the Sum block add two signals and
subtract a third, change the list of signs to the following:
++-
Each element in the list corresponds to one of the signals. Close the dialog box. The Sum
block in your model window should now have three inputs, one of which has a minus sign as
shown below.
Integrator
The output of the Integrator is the integral of the input. An initial condition can be specified,
as well as saturation limits. This block is very useful for modeling systems.
Transfer Function
Numerator and denominator polynomials can be specified to create a standard SISO LTI
system transfer function.
State Space
A, B, C, and D matrices can be specified to create a LTI state space system. Inputs and
outputs may be vector signals depending on the sizes of the matrices.
Zero-Pole
Vector lists of zeros and poles can be specified to create a transfer function. DC gain is also
specified.
Derivative
The output is equal to the derivative of the input.
Dot Product
The output is equal to the dot product of two vector signals.
Matrix Gain
The output is equal to the input times a specified constant matrix. The size of the input and
output vector signals must match the size of the matrix.
Slider Gain
This multiplies the input by a scalar constant which is specified by moving a slider on the
screen as shown below. The limits of the slider can be specified.
Nonlinear
Nonlinear Blocks are elements of nonlinear continuous-time dynamic systems. Most of these
have special-purpose applications and will not be used in the tutorials. Only the most relevant
Nonlinear blocks will be discussed here. Double-click on the Nonlinear icon in the main
Simulink window to bring up the Nonlinear window.
Elementary Math
The output of this block is a basic mathematical function applied to the input. Copy this block
into your model window and double click on it. The resulting dialog box has one field, which
when clicked on, give the following menu of functions.
The desired function can be selected from the list, and the choice will be displayed in the
block in your model window.
Product
The output is equal to the product of the inputs. The number of inputs can be specified.
Fcn
Arbitrary MATLAB expressions can be represented by this block.
Connections
Connection Blocks are used to organize and combine signals and systems. These also have
special purpose applications, and only some of these will be described here. Double-click on
the Connections icon in the main Simulink window to bring up the Connections window.
Subsystem, In, Out
The Subsystem block is used as a system "macro", where one Subsystem block can be used to
represent an entire set of blocks. When double-clicked, the subsystem block brings up a blank
model window. Note that the Subsystem block has no inputs or outputs. For each input a
Subsystem has, an In block is used. For each output a Subsystem has, an Out block is used.
For more information on Subsystems and In and Out blocks, see the Interaction with MATLAB
tutorial page. For an example of the creation of a subsystem, see the DC Motor Speed
Modeling in Simulink example (as well as other examples.)
Mux, Demux
The Mux (Multiplexer) block is used to combine two or more scalar signals into a single
vector signal. Similarly, a Demux (Demultiplexer) block breaks a vector signal into scalar
signal components. The number of vector components must be specified in each case. For an
example of the use of a Mux block see the Bus Suspension Modeling in Simulink example.
Tutorials
MATLAB Basics | MATLAB Modeling | PID | Root Locus | Frequency Response | State
Space | Digital Control | Simulink Basics" | Simulink Modeling | Examples
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 double-clicking
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 double-clicking
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 (right-angled)
route so it needs to be drawn in several stages. Second, there is no output terminal to
start from, so the line has to tap off of an existing line.
To tap off the output line, hold the Ctrl key while dragging the mouse from the point
on the existing line where you want to tap off. In this case, start just to the 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 M ATLAB 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, doubleclick 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.
Tutorials
MATLAB Basics | MATLAB Modeling | PID | Root Locus | Frequency Response | State
Space | Digital Control | Simulink Basics | Simulink Modeling | Examples
Simulink Basics Tutorial - Interaction With
MATLAB
Defining Block Parameters Using MATLAB Variables
Exchanging Signals With MATLAB
Extracting Models From Simulink Into MATLAB
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, double-click
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 double-clicking 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-to-output 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
1
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
0
5.0000
10.0000
1.0000
2.0000
9.0000
10.0000
dencl =
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.
Tutorials
MATLAB Basics | MATLAB Modeling | PID | Root Locus | Frequency Response | State
Space | Digital Control | Simulink Basics" | Simulink Modeling | Examples
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.
Tutorials
MATLAB Basics | MATLAB Modeling | PID | Root Locus | Frequency Response | State
Space | Digital Control | Simulink Basics | Simulink Modeling | Examples
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 statespace 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 mfile, 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.
Modeling Examples
Cruise Control | Motor Speed | Motor Position | Bus Suspension | Inverted Pendulum |
Pitch Controller | Ball and Beam
Tutorials
MATLAB Basics | MATLAB Modeling | PID Control | Root Locus | Frequency
Response | State Space | Digital Control | Simulink Basics | Simulink Modeling |
Examples
Download