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

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.

Simulink is supported on Unix, Macintosh, and Windows


environments; and is included in the student version of MATLAB
for personal computers

1
STARTING SIMULINK
Simulink is started from the MATLAB command prompt

>> Simulink

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

When it starts, Simulink brings up the main Simulink window

and a blank, untitled, model window. This is the window into


which a new model can be drawn.

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

Example:
simple.mdl
The following model window should appear.

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

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.

One exception to this is a line can tap off of another line, splitting
the signal to each of two destination blocks, as shown below

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

Simple Example

The simple model consists of three blocks: Step, Transfer Fcn,


and Scope.

The Step is a source block from which a step input signal


originates.

The Transfer Function linear block. The Transfer Function


modifies its input signal and outputs a new signal.

The Scope is a sink block used to display a signal much like an


oscilloscope.

5
MODIFYING BLOCKS
A block can be modified by double-clicking on it.

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 s2+2s+1, enter the


following into the denominator field: [1 2 1]

6
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 s, from an initial level of zero to a level of 1.

The most complicated of these three blocks is the "Scope" block.


Double clicking on this brings up a blank oscilloscope screen.

7
When a simulation is performed, the signal which feeds into the
scope will be displayed in this window. Use of the autoscale
button, which appears as a pair of binoculars.

8
RUNNING SIMULATIONS
To run a simulation, we will work with the following model file:
simple2.mdl

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

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

9
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)

We can change the parameters of the simulation also. In the


model window, select Parameters from the Simulation menu.
You will see the following dialog box.

10
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.. Change Stop time from 10.0 to 2.0, which should
be only shortly after the system settles.
.

11
BUILDING SYSTEMS
Learn how to build systems in Simulink using the building blocks
in Simulink's Block Libraries.

1. Gather all the necessary blocks from the block libraries.

2. Modify the blocks so they correspond to the blocks in the


desired model

3. Connect the blocks with lines to form the complete system.

4. Simulate the complete system to verify that it works.

12
Gathering Blocks
Create a new model (New from the File menu or Ctrl-N).

Double-click on the Sources icon in the main Simulink


window.

13
Drag the the Sum, Gain, and two instances of the Transfer Fcn
(drag it two times) and a Sink into your model window

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

• Modify the Sum block.


• Modify the Gain block. Change the gain to 2.5.
• Modify the left-most Transfer Function block. Change the
numerator to [1 2] and the denominator to [1 0].
• Modify the rightmost Transfer Function block. Leave the
numerator [1], but change the denominator to [1 2 4].

• Change the name of the first Transfer Function to "PI


Controller", and the name of the second Transfer Function
block to "Plant".

15
Connecting Blocks with Lines
Now that the blocks are properly laid out, connect them together.

The line remaining to be drawn is the feedback signal


connecting the output of the Plant to the negative input of the
Sum block

Finally, labels can be placed in the model to identify the


signals. To place a label anywhere in your model, double click
at the point you want the label to be.

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

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.

17
Taking Variables from MATLAB
In some cases, parameters 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

>> K=2.5

This variable can now be used in the Simulink Gain block.

Re-run the simulation and view the output on the Scope. The
result should be the same as before.

18
Now, if any calculations are done in MATLAB to change any of
the variables used in the Simulink model, the simulation will use
the new values the next time it is run.

>> K=5

Start the Simulink simulation again, bring up the Scope window

19
Simulink Modeling Tutorial
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.

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

We will begin to construct the model simply from

Sum(forces_on_M1)=M1*x1''
Sum(forces_on_M2)=M1*x2''

Constructing The Model


First, we will construct two copies (one for each mass) of the
expressions

a=x’’=1/M*sum_F.

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

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

23
The first force acting on M1 is just the input force, F.

The next force acting on M1 is the friction force. This force is


equal to:

F_friction_1=mu*g*M1*v1

and acts in the negative x1-direction.

24
The last force acting on M1 is the spring force between masses.
This is equal to:

F_spring = k*(x1-x2)
First, we need to generate (x1-x2). 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

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

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

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

Running the Model


Before running the model, we need to assign numerical values to
each of the variables used in the model. 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 variables 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

27
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 Now, run the simulation
and open the View_v1 scope

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

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.

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

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

31
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 saw-tooth
waves as well as a random signal.

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.

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

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.

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

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

35
SINKS
Sink Blocks are used to display or output signals.

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.

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

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

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

39
LINEAR
Linear Blocks are elements of linear continuous-time dynamic
systems

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.

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

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

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

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

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

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

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.

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

47
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
variables in Simulink block dialog boxes.

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 variables, the numerator polynomial, the denominator
polynomial, and the gain. Enter the following commands in
MATLAB to generate these variables.

K=2.5
num=[1 2]
den=[1 0]

48
These variables can now be used in the blocks in Simulink.

Double-click on the PI Controller block. Enter num in the


Numerator field and den into the Denominator field.

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

50
51
EXCHANGING SIGNALS WITH MATLAB
VARIABLES
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.

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

52
Before connecting these blocks to the rest of your system, first
you will name the variable to which they output.

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

54
You can now examine the outputted variab in the MATLAB
window with plot(t,u,t,y);

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

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 and connect an In block from the
Connections window to your model window in place of the Step
block you just deleted.

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

Now, save this model under a new name. Call it mymodel.mdl.

At the MATLAB prompt, LINMOD obtains linear models from


systems of ord. diff. equations (ODEs).
>> [A,B,C,D]=linmod('mymodel')

You should see the following output.

57
A =

-2 -9 2
1 0 0
0 -5 0

B =

5
0
5

C =

0 1 0

D =

>>step(A,B,C,D)

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

58