Professional Documents
Culture Documents
Appendix C - Simulink Refresher
Appendix C - Simulink Refresher
Appendix C - Simulink Refresher
C.1 Introduction
Simulink is a modeling and simulation environment that runs on top of MATLAB; i.e., you need MATLAB
to run Simulink. It has a much different look and feel, as models are created by building a block diagram,
as opposed to typing code. The user interface is therefore graphical, and inherently more intuitive.
Simulink’s user-friendly nature makes it a suitable choice for short-duration training courses, as attendees
Simulink is optimized for modeling dynamic (time-based) systems. It explicitly runs over a simulated time-
duration defined by the user. Internally, Simulink runs a numerical “engine” called the Solver. The Solver
is a numerical integration algorithm that steps through time, calculates the output of each block, and
As one might expect, Simulink interacts closely with MATLAB. Simulink models can access the MATLAB
Workspace, so it may use MATLAB variables either as simulation parameters, or as input signals. Likewise,
it can send its outputs to the Workspace as well. We will see several examples of these interactions.
The rest of this Appendix is organized as follows. Section C.2 offers a walk-through of the Simulink
environment and demonstrates the creation of a simple model, showing several features along the way.
Section C.3 will focus on Subsystems as a way to create layers within the model. Section C.4 discusses
types of multidimensional signals, followed by section C.5 with multiple examples of MATLAB/Simulink
interactions, including the use of Callback functions in Simulink. Lastly, Section C.6 concludes with a look
Throughout this Appendix, we use the Courier New font style to denote MATLAB expressions and
variables.
Page | 1
C.2 Building a Simple Model
The user may start Simulink from the MATLAB Desktop in a number of ways: Clicking on the “Simulink”
button in the Toolstrip, selecting “Simulink Model” from the “New” menu in the Toolstrip, or simply
entering “simulink” in the Command Window. All three methods are highlighted in Figure C.1.
Any of these methods will open the Simulink “Start Page,” which is shown at the top of Figure C.2. Press
“Blank Model” to start a new model. This will open the “untitled” blank model at the bottom of the figure.
Notice that an existing model may be accessed from the “Recent” listing on the left panel of the “Start
Page,” or simply opened from the MATLAB “Current Folder” window like any other file. Simulink files have
a .slx extension; for models created with Simulink versions older than R2012b, the file extension is .mdl.
Page | 2
Figure C.2 Top: Simulink Start Page. Bottom: New model window created by pressing “Blank Model.”
Simulink models are composed of blocks that the user lays out in the blank model and connects as needed.
The Library Browser is a visual catalog of all available blocks, and it may be accessed by pressing the
“Library Browser” button in the blank model Toolstrip, as seen in the figure. The Library Browser window
is shown in Figure C.3. The base Simulink library at the top comes with the Simulink license; it is divided
into sub-libraries (shown indented in the figure) based on logical groupings. The “Sources” sub-library, for
example, contains blocks that start the diagram, while the “Sinks” sub-library contains the terminating
blocks. Other libraries may be purchased separately as Toolboxes. Right-clicking on a block in the browser
displays a menu where the user may access the Help entry for the block.
Page | 3
Figure C.3 The Simulink Library Browser
The Library Browser was the traditional way to copy blocks to the blank model, either by explicitly dragging
them with the pointer (left-click and hold to drag), or through a menu option (right-click on the block and
select “Add to…”). In recent versions of Simulink, the user may simply type the name of the block directly
in the model for the block to appear. This requires double-clicking in the model background to insert a
blinking cursor. As the user starts typing the name of the block, multiple options will show up in a menu,
As a practical exercise, the reader may follow along the following steps in creating a simple model.
Page | 4
a. “Sine Wave” block from “Sources” sub-library
Figure C.4 Top: Block layout for simple model. Bottom: Connected and unconnected wires.
3. Connect the “Sine Wave” to the “Gain”, then the “Gain” to the “Scope”. The blocks may be
a. Manual Connection: Place the pointer at the output port of the source block (the pointer
will turn into a cross-hair symbol). Left-click and hold, then move the pointer towards the
Page | 5
destination block to drag the connecting “wire.” While the wire is disconnected, it looks
like a red dashed arrow. Once the pointer is close enough to the input port of the
destination block, the wire will connect automatically and turn into a solid black arrow.
Both types of wire (connected and unconnected) are shown at the bottom of Figure C.4.
b. Shortcut: Select (click) the source block—It will be highlighted by a surrounding blue halo.
Hold down the Control key (“ctrl”) on the keyboard, and then select the destination block.
4. Modify block parameters. Each block has an associated set of parameters that the user may
modify to suit their needs. For this example, we will only modify the gain value in the “Gain” block.
Open the parameter window by double-clicking on the block. The window will show an edit box
with the default gain value of ‘1’ (which is visible on the block itself). Change the value to ‘10’ and
select “OK.” This will close the parameter window and the new value will show on the “Gain”
Figure C.5 (a) Fully connected model. (b) Parameter window for “Gain” block. (c) Model with updated
gain value.
Page | 6
5. Copy the “Scope” block. Create a copy of an existing block by right-clicking the block and holding,
then dragging the cursor away from it. The user will notice the outline of the block copy moving
with the cursor. Release it just below the first “Scope”. Alternately, use the usual keyboard
shortcuts Ctrl+C for Copy and Ctrl+V for Paste. Notice the label on the copy is “Scope1.” Simulink
appends the number automatically, as blocks cannot share the same name in a model.
6. Create a “branch”. Branches are formed by splitting a wire into multiple paths going to different
destinations. We now create a branch to send the “Sine Wave” signal straight to “Scope1,”
bypassing the “Gain” block. Hover the pointer anywhere on the wire out of “Sine Wave”, then
right-click, hold and drag the pointer towards “Scope1”, as shown at the top of Figure C.6. Once
the branch is close enough to the “Scope1” input port, the connection will complete
automatically. The model should now look like the bottom of Figure C.6.
Figure C.6 Top: Creating a branch from Sine Wave to second Scope block. Bottom: Branch connected.
Page | 7
7. Combine wires to create a non-scalar signal. As currently designed, all signals in the model are
scalar values at every simulation time step. Simulink does support non-scalar, i.e., multi-
dimensional signals, however. They may be generated directly at the source block, or they may
be created by combining scalar signals. In this example, we will use a “Mux” block to combine the
output signals of the “Sine Wave” and “Gain” blocks, and sent them to “Scope1”. The “Mux” block
has a user-defined number of inputs, with a default of two. Insert a “Mux” block and place it just
to the left of “Scope1”. Break the connection between the existing branch and “Scope1” (left-click
and hold the connecting arrowhead, then pull it back), and reconnect it to the bottom input port
of the “Mux”. Next, create a second branch from the wire coming out of the “Gain” block, and
There are a couple of visual aids to indicate there are non-scalar lines in the model. From the
Toolstrip, select the “DEBUG” tab. In the “DIAGNOSTIC” section, open the “Information Overlays”
menu. In the “SIGNALS” section at the top of the menu, select both the “Signal Dimensions” and
the “Nonscalar Signals” options. The model should now look like Figure C.7. The thick black wire
coming out of the “Mux” indicates it carries a non-scalar signal. The labels of ‘2’ at both ends of
Page | 8
the wire are the signal dimensions. Once this option is selected, any wire with no dimension label
8. Run the model. Save the model as “vector_examp”. Select “Run” from the Toolstrip. To observe
the results, the user must open the “Scope” screen windows by double-clicking on the blocks, as
Figure C.8 Results from “vector_examp” simulation run. Left: “Scope” window with sine wave scaled by
“Gain” block. Right: “Scope1” window with both scaled and original sine wave signals from “Mux”.
The user may zoom in and out of the model using the mouse scroll wheel. Alternatively, the user may use
the shortcut keys Ctrl++ (“Control” key simultaneously with “plus” key) for zooming in and Ctrl+- for
zooming out. There is also a “magnifying glass” zoom utility on the left side panel of the model, which
Another useful utility is the “Fit to View” button, which is right below the zoom button on the left panel.
Page | 9
Annotations
Simulink offers many options for annotating the model. All blocks may be renamed as desired by the user.
Likewise, each wire may also be labeled by double-clicking on it, which inserts a blinking cursor. The wire
label (which becomes the signal name) may be replicated on each branch by right-clicking on the label
Free-floating text boxes may also be added to the block by double-clicking anywhere in the model
background. This is the same action used to add a block, but instead of typing a block name, the user may
enter a suitable comment. Alternatively, there is an “Annotation” button on the left panel of the model.
These comments may be formatted as needed by right-clicking on them and choosing the desired options.
Simulink supports TeX commands, meaning equations may be written using actual mathematical symbols.
Lastly, Simulink offers a couple blocks in the “Model-Wide Utilities” sub-library, which are useful for
adding additional documentation. The “DocBlock” block allows the user to enter text and save it with the
model. The “Model Info” block displays model information such as the model creator, model version,
Simulink allows the model designer to organize the block diagram by grouping blocks together and
encapsulating them into a single block called a “Subsystem”. This adds an additional layer of depth to the
model, and improves readability by decreasing the block density at the top level. The designer may
organize highly complex models into multiple nested subsystems, and easily navigate from one layer to
another.
Using “vector_examp” as an example, we now create a “Subsystem” containing the “Gain” and “Mux”
blocks plus the two branch points. First, select the section to be encapsulated by left-clicking and holding,
Page | 10
then drawing a box around them and releasing. A “Multiple” tab will show up on the Toolstrip; select it,
then select the “Create Subsystem” option. Figure C.9 shows an annotated version of “vector_examp”
Figure C.9 Creating a “Subsystem” in “vector_examp” from existing blocks: (a) Original (annotated)
model; (b) Model after “Subsystem” is created; (c) Contents of “Subsystem” block.
The user may navigate inside the “Subsystem” block by simply double-clicking it. The numbered oval
blocks in Figure C.9(c) are input and output ports. They inherit the signal labels if there are any defined
when the “Subsystem” is created; otherwise, they get generic, indexed labels (such as “Out2” in C.9(c),
since its corresponding wire has no label). Additional navigation tools include the blue arrows in the upper
left of the model box right below the Toolstrip; however, the best way is to use the “Model Browser.” This
browser is accessible by selecting the double arrowheads (>>) at the bottom of the left side panel. The
Model Browser is shown in Figure C.10, and displays an indented listing of model subsystems as distinct
layers in the model. The user can quickly navigate up and down the model by selecting the desired
Page | 11
layer/subsystem. Similar to a Windows File Explorer window, the user may expand or collapse portions of
A second way of creating a subsystem in the model is to build it from scratch, by adding an empty
“Subsystem” block from the “Ports and Subsystems” sub-library, then adding blocks to it as needed.
“Muxing” together two scalar signals in “vector_examp” was a quick way of creating a multi-dimensional
signal. Another approach is to create them right at the source by defining a block parameter as a vector
instead of a scalar. To illustrate, open the parameter window for the “Sine Wave” block. In the
“Amplitude” box, change the current value of ‘1’ to the two-element vector [0.5 1] as shown in Figure
C.11(a). Re-run the model and see how the dimensionality changes starting at the source.
One key point with multidimensional signals is whether Simulink interprets them as vectors or not. Notice
the checkbox labeled “Interpret vectors parameters as 1-D” at the bottom of the parameter window in
C.11(a). The default setting for the box is to be checked, and in that case, the signals are interpreted as
individuals scalars grouped together, as opposed to being a “vector” in the mathematical sense. If the
Page | 12
user unchecks the box and re-runs the model (Try it!), the dimension labels will be as shown in C.11(c),
showing the signals explicitly as row vectors ([1x2] or [1x4]). This is the required setting if the model
performs any linear algebra operation on these signals. Since “vector_examp” does not, the model
Figure C.11 Generating vector signals from the source: (a) Parameter window for Sine Wave block; (b)
Signal dimensions when interpreted as 1-D; (b) Signal dimensions when not; i.e., when interpreted as
vectors.
As a counter-example, the reader is encouraged to open and run the model “vector_examp2”, which
includes a vector multiplication. In this case it is important to uncheck the vector parameters
interpretation box, otherwise the model will crash at run-time (Try it!). The model and results for each of
the two options are shown in Figure C.12. Note that the top-to-bottom order of the input ports in the
“Matrix Multiply” block corresponds to the left-to-right order of multiplication if the equation were
written.
Page | 13
Figure C.12 Model “vector examp2” with unchecked box shows vector dimensions (a) and results in
correct vector multiplication (c). Same model with boxed checked (b) results in inconsistent dimensions
causing a run-time error (d).
Another type of multi-dimensional signals are those carried by “buses”. A bus is useful for grouping and
transporting signals; it is formed by combining signals using a “Bus Creator” block, which is somewhat
similar to a Mux block. A bus, however, is more flexible and convenient, and coupled with signal labels,
allows better signal management by the user. Figure C.13 shows the block diagram for the model
“Bus_Example.” The first “Bus Creator” block combines three scalar signals into a three-element vector.
The second “Bus Creator” combines the newly formed vector with an additional scalar signal. The
parameter windows shown at the bottom list the signals contained in the bus at any time.
Page | 14
Figure C.13 Bus example showing Bus formation and signal extraction. Signal labels are not required but
are helpful for management and readability.
Individual (or subsets of) signals are extracted from the bus using a “Bus Selector” block. The parameter
window for this block shows the signals in the bus, and allows the user to select which signals will be
extracted (scalar “a” in the figure). In the block diagram, Simulink automatically adds the signal label <a>
to the “Bus Selector” output wire. For vector signals, individual elements may also be extracted. The
“vector” signal listed in the “Bus Selector” parameter window may be expanded using the drop-down
menu arrowhead, and the individual elements would show as “vector.x”, “vector.y” and
“vector.z,” respectively. Thus, the bus construct may be seen as the Simulink equivalent of a MATLAB
structure.
Page | 15
The last multi-dimensional signal type considered here are “frame-based” signals. Frames are
fundamentally different from previous multidimensional signals. While those previous examples may be
interpreted as values from multiple data channels at each instance of time, a frame is a group of data
samples from the same channel collected over multiple times. Thus, a frame is simply a batch of time
Fr = Fs / L (C.1)
where F s is the individual sample rate and L is the length of the frame; i.e., the number of samples it
contains. For example, if the individual rate is 1 sample per second, then one frame of L = 8 samples will
Frame-based signals may be generated by certain source blocks, or may be created by buffering individual
samples. Both of these methods are demonstrated in the model “frame_vs_sample_examp.” Figure C.14
shows the block diagram and results. Notice the signal dimensions on the wires.
Figure C.14 Frame-based signal example. (a) For a 0 sec stop time, the source-based frame provides an
output, but not the buffered version due to latency. (b) For an 8 sec stop time, buffered version provides
an output, but source-based version has already advanced to the next.
Page | 16
The top version takes a sample-based (scalar) signal from a standard “Sine Wave” block at a 1 sec sample
rate and feeds it to a “Buffer” block, which is set to collect L = 8 samples. The buffer will not generate an
output until it is filled up, meaning it will take 8 sec to do so. The bottom version uses a “Sine Wave” block
from the “DSP System Toolbox,” which allows the user to define a frame right at the source. This block
will output its first frame at time = 0. Both of these frames run at the same rate of one output every 8 sec,
so the buffered version will always trail the source-based version due to the initial lag in filling up the
buffer.
Frames are useful when the model requires operating on multiple samples simultaneously; for example,
Page | 17
Instead of using constants as block parameters, a user may conveniently defined them as variables. Since
Simulink can access the MATLAB Workspace, model and block conditions may be quickly modified by
Figure C.15 shows a modified version of “vector_examp” where the parameter in the “Gain” block is now
the variable “a”. The variable is defined and easily updated from the MATLAB Command Window. Block
parameters are not limited to just MATLAB variables; in fact, any valid MATLAB expression such as
One downside of this approach is the possibility of an oversight in initializing the variables, which would
C.5.2 Running MATLAB code from within the Simulink block diagram
The “User-Defined Functions” sub-library offers several blocks used to run MATLAB code from a Simulink
model. Model “fcn_examp” demonstrates two example blocks, as shown in Figure C.16. The model takes
a two-element vector created by a “Constant” block, and computes their average value (1.5 in this case).
The first block used to perform this operation is an “Fcn” block. Its usage is straightforward, as it simply
evaluates a general MATLAB expression. The user must type the expression inside the block parameter
window, using “u” as the input variable name. This seemingly small detail tends to trip beginner users.
Page | 18
Even if the wire leading to the “Fcn” block has a label, that label is unknown to the block; the block only
knows the input values as “u.” If the input is a vector, standard indexing notation applies. For example,
Figure C.16 Selected options for running MATLAB code from Simulink.
The two blocks below the “Fcn” block are copies of the “Interpreted MATLAB Function” block. This very
versatile block enables the user to call any function from the MATLAB library, or to call a user-defined
function m-file. The middle block calls the built-in function “mean,” while the bottom one calls the user-
defined “mymean,” available in “mymean.m”. This block opens a whole new set of possibilities by adding
As a follow-on to the previous example, one common application of the “Interpreted MATLAB Function”
is to add a user-defined function to perform plotting. Native Simulink graphics options such as the “Scope”
Page | 19
block are relatively crude and with limited formatting options, meant primarily as a “quick look” to verify
correct model operation and results. Through an “Interpreted MATLAB Function” block, the full power of
MATLAB graphics is available for creating figures suitable for formal technical presentations and other
purposes. The model “Plot_Sim_Examp” shown in Figure C.17 illustrates this point. Three different sine
waves are observed on a scope, as well as plotted using MATLAB commands. Notice that since the sine
wave signals are sampled-based, they must be buffered before creating the time-based figure in MATLAB.
Page | 20
C.5.4 Running Simulink from MATLAB
The converse of the previous two examples is also true: One can run a Simulink model from MATLAB. The
key MATLAB function is “sim.” Just like any other function, it may be called from the MATLAB command
line or from an m-file. At the very least, the user must provide the model name as an input argument in
Other optional input arguments are available, for which the reader is referred to the corresponding online
documentation.
This is the approach used in the GUI-driven waveform generator model “wavegen” presented in Chapter
The block “From Workspace” available from the “Sources” sub-library allows Simulink to read existing
data in the MATLAB Workspace and propagate it through the block diagram. The data may be formatted
as either a timeseries, a matrix, or a structure. Figure C.18 shows the model “inwork_examp”
demonstrating this functionality. Prior to running the model, the following commands must be issued in
>> t = 0:0.1:10;
>> x = sin(t);
>> simin = [ t' x' ];
Notice the transpose operators for vectors “t” and “x” to turn them from row into column vectors.
Page | 21
Figure C.18 Input signals to Simulink from Workspace.
Model “outwork_examp” is the converse of the previous example. It uses the block “To Workspace” from
the “Sinks” sub-library to send data created in Simulink to the Workspace. The model is shown in Figure
C.19. After running this model, data vector “simout” and time vector “tout” will be available in the
Callbacks were discussed in the MATLAB Appendix in the context of GUI actions. Simulink also features
Callbacks, both at the model and individual block level. Here we only consider model-level Callbacks.
Page | 22
Callbacks enable the user to execute actions at specific points or events, such as when the model is first
opened; when it starts or stops running; when it is saved or closed, etc. The actions are defined in terms
of MATLAB commands that the user must write, so this may be seen as an extension of section C.5.2
(Running MATLAB code from Simulink). However, one important distinction is that while C.5.2 refers to
MATLAB code as part of the block diagram; i.e., operating on the Simulink signals themselves, here we
Callback functions are defined in the “Model Properties” window, which may be accessed in at least three
different ways. The easiest one is to simply right-click anywhere in the model background, then select
“Model Properties” from the menu that appears. This opens the window shown in Figure C.20,
corresponding to “vector_examp.” Selecting the “Callbacks” tab shows the list of available functions.
Figure C.20 (a) “Model Properties” window when it first opens on the “Main” tab. (b) “Callbacks” tab
showing the available model-level Callback functions.
The box area to the right of the Model callbacks list is the area where the user would write the MATLAB
code for the Callback. The user should be careful in ensuring they write the code in the correct Callback.
In C.20(b), the line at the top of the box reads “Model pre-load function,” which is easy to miss. To write
a different Callback, for example an Initialization (“Init”) Callback, the user must select (click) “InitFcn”
from the list, then the top of the box will read “Model initialization function:” instead.
Page | 23
The user may write MATLAB commands explicitly in the box, or write them in a script m-file and specify
the script name in the box. One straightforward but useful example of an “InitFcn” Callback is to initialize
all the block parameters that use MATLAB variables, as discussed in section C.5.1. This Callback executes
automatically upon the user pressing the “Run” button. Setting an “Init” script to define model parameters
can potentially minimize human error by eliminating the requirement to manually defining them prior to
running the model. This approach is used routinely in this book’s models.
Another Callback example used when the model creates MATLAB figures is to close them when the model
is closed. This is achieved by setting the “CloseFcn” Callback to execute a “close all” command.
This tutorial has only scratched the surface in presenting Simulink functionality. Again, the objective is not
to serve as a comprehensive treatise, but to offer the Simulink novice the minimum information to
negotiate the models in this book successfully. There are a few additional features that are used in this
book:
• Enabled Subsystems: These are subsystems that execute based on an external control signal going
“high,” i.e., becoming greater than zero. The waveform generator Simulink model from Chapter 7 is a
• Masked Subsystems: A mask may be added to any subsystem, which gives it a similar look and feel as
a library block. When double-clicking a masked subsystem, instead of opening the subsystem to view
its content, the mask appears, looking similar to a parameter window from a library block. The mask
is highly customizable to set up initial conditions, a block description, and other useful features. The
object (target and radar) dynamics blocks used to test the “Target Generator” model in Chapter 14
Page | 24
• User-defined libraries: A user may create reusable custom blocks and place them in a user-defined
library. The library file may be created from scratch from the Simulink Start Page. Simulink also offers
information on adding the user-defined library to the Library Browser for easy access. The object
(target and radar) dynamics blocks used to test the “Target Generator” model in Chapter 14 are
custom masked subsystems that exist in the user-defined library “MS_Models”. This library is shown
in Figure C.21.
Figure C.21 User-defined library “MS_Models.” The three Dynamics blocks on the left are masked
subsystems.
The following features are not used in the book examples, but are mentioned here for general reference.
Page | 25
• Debugger: The Simulink Debugger allows the user to step through the model one block at a time,
and then examine the model conditions and signals as needed. The user may insert break points,
overwrite values, and perform other actions similar to the MATLAB debugger.
• Atomic Subsystems: Subsystems that are evaluated as a single unit, as opposed to regular
subsystems (called “virtual” subsystems) where the execution order of the model may be such
that it goes into and out of the subsystem multiple times. All Enabled and Triggered Subsystems
are Atomic Subsystems. A virtual (regular) subsystem may be treated as an Atomic Subsystem if
• Block-level Callbacks: Each Simulink block can have its own set of Callback functions. The Callbacks
list may be accessed by right-clicking on the block and selecting the “Properties…” option from
the menu. This will open the window shown in Figure C.22, which corresponds to the “Gain” block
in “vector_examp.”
• S-Functions: S-Function (or “System Function”) blocks provides a way to bring in legacy code
written in other languages such as C, C++ and FORTRAN and run it from the Simulink model. S-
Functions serve as a “wrapper” to these external programs, which are compiled as MEX files using
Page | 26
Figure C.22 Block properties window with block-level Callbacks list.
Page | 27