Details of Using SIMULINK
Details of Using SIMULINK
TODAY’S
PRESENTATION
Presentation Topic:- Details of Using
SIMULINK
Submitted by: Submitted to:
My Best Wishes
-----Professor Dr. Li ShaoFu.
Table of Content:
Signal Routing & Logical
Introduction
Integration & Differentiation
MATLAB & SIMULINK Working Together
What is SIMULINK?
Constructing And Simulating a Simple Circuit
Working With Blocks
Model
Block Settings
Example Models
Model Annotation
SIMULINK Shortcuts
The Solver
The Solver: Zero-Crossing Options
Sources Library
SIMULINK Online Documentation
Sinks Library
Further Examples
Math Operation Library
Conclusion
User Defined Functions & Lookup Tables
References
Ports & Subsystems
Introduction:
This document is part of the “Details of Using Simulink” seminar. This seminar is designed for
people that have never used Simulink. There are two components to the seminar. SIMULINK is far
more useful for control system simulation. SIMULINK enables the rapid construction and simulation
of control block diagrams. There are exercises in a separate document that will take you step by step
through the tasks required to build and use a Simulink model. Once you get started using Simulink,
you will find a lot of the functionality is self-intuitive. Inevitably, there are things that need a bit
more explanation. So the other part of the Seminar is a talk and demonstration. This document
contains the notes for the talk.
It would be impossible to put everything about Simulink into such a short document, so this
document concentrates on the parts of the package that are considered the most useful. It also aims to
highlight features that are not obvious to the casual user.
The intention is that you use these notes as a reference when carrying out the exercises and when
building your own models. Although these notes have their limits, I hope that they should be
sufficient to get you started using the package and that they cover most of your modelling needs.
This is not a Simulink manual. Sooner or later you will need to know more detail about something
within Simulink. This document is intended to be used in conjunction to the documentation
available within the package. MathWorks, creators of MATLAB & Simulink, provide extensive
online documentation for Simulink that can be accessed using the MATLAB help system. There is
so much online documentation that not many people have the time or inclination to read all of it.
So an aim of the Seminar is to emphasize the things that you ought to know about Simulink and to
give you some idea about where you can find any other information that you require.
What is SIMULINK?
SIMULINK is a visual programming interface designed to make modelling systems intuitive. It
offers a way to solve equations numerically using a graphical user interface, rather than requiring
code. Models contain blocks, signals and annotation on a background:.
Blocks are mathematical functions, they can have varying
numbers of inputs and outputs.
Signals are lines connecting blocks, transferring values
between them. Signals are different data types, for example
numbers, vectors or matrices. Signals can be labelled.
Annotations of text or images can be added to the model,
and while not used in the calculations they can make it easier
for others to understand design decision sin the model.
Start MATLAB, then start Simulink
The Simulink Toolbar:
Build Model
Model Settings Run Model If your model is
All of the settings related To run the simulation, press the interacting with
to how to numerically green arrow. Be aware there are hardware, you will need
solve the equations of the different modes e.g. ‘Normal’. If to build the model before
model are found in you are working with hardware it can run. The current
“Model Configuration the mode will be ‘External'. The status is shown in the
Parameters” Cog. textbox is how many seconds lower left of the Simulink
you want the simulation to run window.
for.
Working with Blocks:
Adding Blocks to Model:
There are two ways to add blocks to a model: the Library Browser or the Quick Search:
Library Browser
Shows all blocks available in Simulink, sorted by folders such as ‘Math Operations’
or ‘Signal Routing’. There is a search bar on the top left. Drag blocks from the
library straight onto your model canvas.
Quick Search
Directly search for blocks by single clicking on the background of your model and
typing in a search term. Select a block from the search results to quickly add it to
your model.
Automatic Block Input Box:
When adding a block to a model for the first time, the most common parameter will often pop up automatically
for a value to be specified. e.g. If you add a Gain Block it will ask you to specify the gain value. Interacting with
this can save time opening the Block Parameters menu
Positioning Blocks:
Blocks can be moved by simply clicking and dragging.
Connect blocks by clicking output of one block and dragging it to an input of another block.
Once a signal connects two blocks, it can be clicked and dragged to be repositioned.
To create a branch from an existing signal, hold ctrl while clicking and dragging.
Blocks can be rotated/flipped for better positioning: Right click block, select “Rotate & Flip”.
Block Settings:
Each block has its own settings in Block Parameters and Block Properties
Model Annotation:
The Solver:
Most of the time, you can just use the default settings to run your model. However you will sometimes find that you will want the
model to use smaller steps, or fixed width steps. This is all configurable on the Solver page of the Configuration Parameters.
From the menu bar on your model select Simulation ► Model Configuration Parameters
Or simply use the shortcut on the toolbar
Once opened,
select Solver.
There are many
configurable
settings
Start/Stop time: It is suggested that you leave the start time as zero. The stop time is same as in the
toolbar at the top of your model.
There are two types of solver:
1. A variable step solver (the default): This will automatically adjust the step size as the model runs.
If you are using variable step generally keep the default solver (ode45). Set the Max step size to a
small fixed value to improve the smoothness of any plots.
2. A fixed step solver will be necessary for models with discrete components. If it also has no
continuous components, change the solver to Discrete (no continuous states)and set the step size to
a known value. The fixed solvers are numbered in order of simplicity,ode1being the simplest.
Zero-crossing options: Under “Additional Parameters” you will find the Zero-crossing options.
Further details about zero-crossing are found on next. For more information about solvers, click on
the Help button at the bottom of the configuration parameters window, while you are viewing the
solver section
Sources Library:
Source blocks provide different signals for your model.
SIMULINK Sources
Sinks Library:
Scope plots inputs against time. It has an extensive toolbar.
The Logging Tab contains a tick box to ‘Log data to workspace’. If this
is enabled then whenever the simulation is run, a variable is
automatically populated in the MATLAB workspace. You can name the
variable and set the datatype.
Plots the top input X against lower input Y in a figure within Simulink.
Cannot easily change the axis labels or titles, so it is better to use the To
Workspace block to send data to MATLAB, then plot there.
The add, subtract and sum blocks are all essentially the same. By
changing the icon shape and list of signs in the block parameter you can
convert one into the other (see right).
Product and Divide Blocks:
The Product and Divide blocks are also interchangeable. You can use a list of asterisks and forward slashes in the
number of inputs block parameter to define operations needed e.g. Block to the right was created by number of inputs
= /*/**
Gain Block:
The Gain block can be used to multiply a signal by a constant value. You must configure the Block Parameters to
perform matrix or element-wise (array) multiplication.
Array and Matrix Multiplication:
For a Gain block to contain a matrix or vector, simply use MATLAB notation. For example [5678] is entered as [5, 6; 7, 8] –
commas separate row elements and semi colons separate columns.
Mathematical Functions:
There are lots of blocks for specific mathematical functions:
The Abs block finds the magnitude or absolute value of a signal, the Unary
Minus block negates a signal and the Bias block adds a constant to a signal. The
Sign block outputs +/- 1 depending on the sign of the input.
There are also blocks with multiple functions to choose from:
The Math Function block can perform many different functions: square, square root, log,
reciprocal etc. A block parameter allows you to select which particular function you want. The
Trigonometric Function block operates in a similar manner but for cos, sin, tan-1 etc.
User Defined Functions & Lookup Tables:
User Defined Functions:
Sometimes you cannot find the exact function that you want. If this is the case, then try the block called Fcn.
This allows you to enter a mathematical expression using a restricted set of operators and functions:
To see what is allowed, click on the Help in the block parameters. If you need something a bit more
complicated then you can write your own MATLAB function and use the block MATLAB Fcn:
This block has been configured to call the MATLAB function myabs, shown left. x is
the input and y is the output.
Notice that the MATLAB function is not stored as a .m file in the working directory,
instead, you are editing code stored within the block itself. This can be seen from the
Block: My Model/MATLAB Function.
Look Up Tables:
If all else fails, then you can use a look up table to define your function.
You need two vectors to do this. A vector of input values and a vector containing the table of corresponding
output values. You enter these in to the appropriate block parameter. For intermediate values, the output is
calculated using interpolation. Extrapolation is used to calculate values beyond the specified input range. There
are a range of look up tables to suit different needs (e.g. 1-D Lookup Table, 2-D Lookup Table), see the
documentation for further details.
Ports & Subsystems:
A subsystems is a collection of blocks grouped together to carry out a particular task.
They help to keep models organized and easier to understand. The example subsystem
on right takes two inputs. It doubles the first input, quadruples the second input and
outputs the sum.
Creating a Subsystem:
Drag in a Subsystem block from the Ports and Subsystems library
OR
Select the blocks that you want to put into a subsystems and right click then select Create Subsystem from Selection in the
menu that appears.
You can have many nested subsystem (i.e. a subsystem in a subsystem).
Once you have a subsystem, you can open it by double clicking the block. This opens a new tab showing the blocks of the
subsystem. Exit the subsystem and return to the top page by:
Selecting the ‘Up to Parent’ arrow
OR
Selecting the home tab, e.g. ‘My Model’
Input and output ports are called In and Out. If you need extra input/output ports,
they can be found in the Ports and Subsystems library or the relevant Source / Sink
library.
Trigger, Reset and Enable Inputs to Subsystems:
You may need a part of your model to only occur when an appropriate signal is
applied, or for blocks to reset at certain time intervals. For this you place an
Enable, Trigger or Reset block inside the subsystem. These will create an
appropriate input port on the subsystem.
There is extensive documentation on the MathWorks website giving comparisons
of each of these subsystems. A summary is given below:
Enabled Subsystems: Subsystem only runs when signal is 1 through the enable input, a 0 will disable
it. The block parameters of the output ports allow configuration to either hold the current value or reset
to a specified value when the subsystem is disabled.
Triggered Subsystems: Executes one step each time the appropriate signal is applied to the trigger
input. You can configure the trigger input to react to a rising edge, a falling edge or both edges.
Resettable Subsystems: Executes at every time step but conditionally resets the states of blocks within
it to their initial conditions when a trigger event occurs at the reset port.
Masked Subsystems:
A mask is special type of subsystem. It offers a custom interface for a subsystem and hides the content, making it
appear as a built in ‘base’ block with its own icon and custom parameter dialog box. It simplifies the graphical
appearance of a model and controls access to the block content.
Consider an example subsystem below which simply produces a straight line 𝑦=𝑚𝑥+𝑐 where 𝑥 is the simulation
time steps and 𝑚 and 𝑐 are defined by Gain and Constant blocks respectively. To edit 𝑚 and 𝑐 you would normally
have to open the subsystem, and interact with each of the block parameters (this involved multiple windows and
clicks).
If we instead turn this subsystem into a mask (right click -> Mask -> Create Mask) then we could create a custom dialog block.
Whenever we click on this new masked subsystem, we would get one dialog box where we can conveniently set 𝑚 and 𝑐.
The case statement is performed in a similar way. There are two different blocks. The Case block itself determines which of the Case
Action subsystems to perform.
Signal Routing & Logical:
Mux & Demux : Group signals of same type:
A mux block groups multiple signals of the same type. In Block Parameters you specify the Number of Inputs to group.
You can feed a mux output directly into a mathematical block so that the block will operate on all signals at once.
A demux block separates out individual signals. Specify the Number of Outputs in block parameters - this can be a single
integer or a vector. Each number in the vector specifies the number of signals in a particular output.
To overcome possible dimension mismatch errors created by using buses and mux blocks
in the same model, it is helpful to visualize Mux and Bus signals. To give a different style
to each signal type set:
Display > Signals & Ports > Wide No scalar Lines
Switches:
The simplest is the Manual Switch. A user double clicks the block to divert the signal between two paths.
The output of the Switch block is determined by the centre pin. A comparison is carried out between the
centre input and a threshold value. You can select the threshold value and for the comparison to be ≥,≤,=,
etc. If the comparison is true, the output is switch to the top input, else the output is connected to the
bottom input.
Selectors : Accessing specific signals
In MATLAB to access the 3rd and 6th elements of a vector, V say, we would use index notation: V([3 6]). Selectors are the Simulink
equivalent of these indices in MATLAB:
Constant source with "Interpret vector parameters as 1-D" option not checked;
Go to / From Blocks: Move signals without connecting wires
Another way to move signals around is to use Go to and From blocks. Send a signal to a Go to block, where it is given a unique tag.
Then a From block can be configured to use this same tag and access the signal. A simple example is given below. These blocks can
be used to avoid complex signals crossing, and even work to get signals out of subsystems.
Compare To…
These blocks compare a signal with either zero, a constant or another signal. The particular operation
(greater than, equals to etc.) is selected by a block parameter. The output is a Boolean.
Logic Operator:
The Logical Operator block carries out the same operation as a Boolean logic
gate. The logic operation e.g. AND, OR, NOT etc. is selected from block
parameters.
The first two blocks (above) are AND blocks with different block parameter settings. The first has default rectangular icon shape, the
second has the icon shape set to distinctive. The last two are XOR with three inputs (rectangular and distinctive shape).
Integration and Differentiation:
There are continuous and discrete integrator and derivative blocks.
Continuous Integrator:
There are various ways of configuring integrators with extra functionality using block parameters:
By default, the Initial Condition is set within the block, however it can be set as a block input.
(set Initial Condition Source to External)
Limit the output to a maximum and minimum value (tick Limit Output, adds saturation icon
to block).
You can add an external reset signal, to force the output of the integrator back to its initial condition. You can configure the reset pin
to act on a rising edge, falling edge or both.
Discrete Integrator:
For the discrete integrator block, you can specify whether to use forward or backward Euler, or the Trapezoidal method. As with the
continuous integrator block you can specify in the block parameters if you want to define initial conditions externally or internally,
set upper and lower limits and set up a reset condition. You can also define an input gain value.
Continuous Derivative:
The derivative block approximates the derivative of the input signal 𝑢 with respect to the time 𝑡, by computing a
numerical difference. Here 𝛥𝑢 is the change in input value and 𝛥𝑡 is the change in time since the previous simulation
(major) time step:
𝑦(𝑇𝑐𝑢𝑟𝑟𝑒𝑛𝑡)=Δ𝑢/Δ𝑡=𝑢(𝑇𝑐𝑢𝑟𝑟𝑒𝑛𝑡)−𝑢(𝑇𝑝𝑟𝑒𝑣𝑖𝑜𝑢𝑠)/𝑇𝑐𝑢𝑟𝑟𝑒𝑛𝑡−𝑇𝑝𝑟𝑒𝑣𝑖𝑜𝑢𝑠
The initial output for the block is zero.
Discrete Derivative:
The discrete derivative block computes an optionally scaled discrete time derivative with output:
𝑦(𝑇𝑐𝑢𝑟𝑟𝑒𝑛𝑡)=𝐾𝑢(𝑇𝑐𝑢𝑟𝑟𝑒𝑛𝑡)/𝑇𝑠−𝐾𝑢(𝑇𝑝𝑟𝑒𝑣𝑖𝑜𝑢𝑠)/𝑇𝑠
where 𝑇𝑠 is the fixed simulation time step.
Note on accuracy of derivatives: It is best practice to structure your models to use Integrators instead of Derivative
blocks, as Integrator blocks have states that allow solvers to adjust step size and improve accuracy of the simulation.
The derivative block output might be very sensitive to the dynamics of the entire model. The accuracy of the output
signal depends on the size of the time steps taken in the simulation. Smaller steps allow a smoother and more accurate
output, however unlike with blocks that have continuous states, the solver does not take smaller steps when the input
to this block changes rapidly.
MATLAB & SIMULINK Working Together:
While Simulink is useful for modelling and visualizing processes such as feedback loops, detailed data analysis and generation of
good quality figures is still best completed within MATLAB. You can run Simulink models and export the results to MATLAB or run
Simulink models from MATLAB.
Exporting Simulink Data to MATLAB
There are multiple ways to get data from a Simulink to MATAB:
Scope Block: You can enabling data logging from a Scope block within the Configuration Menu Logging tab.
To Workspace block: Once this block is used in your model, each time you run your model two variables are created in the
MATLAB workspace:
tout – column vector of time steps
simout – variable storing simulation data
Use a Mux if you need more than one output.
The simulation data can be of type timeseries, array or structure, as set in ‘Save Format’ in Block Parameters.
Accessing your data in MATLAB depends on the variable type you set.
After running the simulation command above, you can define the vector of time steps as:
t =s.get('tout’)
And the columns of signal data as:
y = s.get(‘simout’) if ‘Save Format’ is array
y = s.get(‘simout’).Data if ‘Save Format’ is structure
y = s.get(‘simout’).signals. Values if ‘Save Format’ is timeseries
Running Simulations from MATLAB:
You can also run your Simulink models using commands from MATLAB. The most basic way is to use the sim command with two
outputs and one input (the model file name as a string):
[t,y]=sim('model')
where tis a column vector of time steps and y is a corresponding matrix with columns of signal data. The sim command can also be
used with other inputs that allow the control of simulation run time for example, but only one output must be assigned. The extra
inputs are known as ‘name-valued pairs’ as a condition is specified and then the value set. For example:
s = sim('model',’StopTime’,’10’,’MaxStep’,’0.1’)
When using a single output, the Simulink model must also be set up to export data in some way, otherwise s will only give a vector of
timesteps. This can be done by adding a ‘To Workspace’ Block, as described above, or adding Output Ports to the Simulink model.
Constructing And Simulating a Simple Circuit Model:
Auto scale
The above shows the general approach to modelling dynamic systems. You calculate the force, use Newton’s 2nd law to calculate the
acceleration, integrate to get the velocity and then integrate again to obtain the position.
The above model is a general guide, it can get a bit more complicated. For example, the mass is required to calculate gravitational
forces. It is also possible that the mass will be a function. For example, a rocket losses most of its mass as the fuel is burnt off.
Example 2: Ordinary Differential Equations (ODE)
The general rule for solving differential equations is to write the equation in terms of the highest differential. For example, consider the
general second order equation below.
𝑦⃛+𝑎𝑦̈+𝑏𝑦̇+𝑐𝑦=𝑓(𝑡) (1)
𝑦⃛=𝑓(𝑡)−𝑎𝑦̈−𝑏𝑦̇−𝑐𝑦
You then use integrators to obtain lower terms:
The right hand side of the equations is formed by feeding back these terms to form the expression required.
Notice that the model contains no differentiators, even though we are modelling a differential equation. Models with differentiators
tend to produce a lot of noise, so are avoided if possible.
The next example is not linear or time invariant:
𝑦̈=𝑦̇^2−𝑡𝑦 (2)
For More & Details Examples Follow PDF File (Page No. 20 to 24)
SIMULINK Shortcuts:
This section contains the short cut keys that
can be used to build and edit your model.
For more details select from the model
menu bar Help ► Keyboard Shortcuts
The Solver: Zero-Crossing Options:
A variable-step solver dynamically adjusts the time step size, causing it
to increase when a variable is changing slowly and to decrease when
the variable changes rapidly. This behavior causes the solver to take
many small steps in near a discontinuity because the variable is
rapidling in this region. This improves accuracy but can lead to
excessive simulation times.
Simulink uses a technique known as zero-crossing detection to
accurately locate a discontinuity without resorting to tiny time steps.
Usually this technique improves simulation run time, but it can cause
some simulations to halt before the intended completion time.
Understanding how Simulink’s zero-crossing detection algorithms, adaptive and non-adaptive, work is beyond the
scope of the course.
The table below should help you overcome some errors associated with zero-crossing, particularly a halting model.
Implementing most of the changes, involves using the Model Configuration Parameters dialog (MCP) box,
accessed via the Cog symbol.
Simulink Online Documentation:
The full Simulink documentation is available from the help menu. You can obtain this from the MATLAB help, or you
can go directly to the Simulink help. From the model menu bar select,
Help ► Simulink ► Simulink Help
Block Documentation
The easiest way of obtaining the documentation for a particular block is to hit the help button in the block parameters.
An alternative is to select the block and then select,
Help ► Simulink ► Blocks & Block sets Reference
from the model menu bar. If no block is selected when you do this, then you will be given a list of all the blocks. You
can then select the documentation you want from this list. At the top of the list, on the right hand side you can choose
to display by Category or in Alphabetic order.
In the Help Menu you will also find links to Web Resources.
Help ► Web Resources
Particularly useful MATLAB Central which is the hub for the online MATLAB and Simulink community. Here you
will find “MATLAB Answers” where people ask for support on MATLAB & Simulink. Once you become confident
with MATLAB and Simulink you may wish to explore the File Exchange, where people upload custom files.
Further Examples:
Simulink Onramp:
In MATLAB 2018b, you can complete the Simulink Onramp course created by
MathWorks. It is around 3 hours of good quality content designed to introduce you to
Simulink. It will give you more practice at a similar level to the exercises in this
course.
You can access this by installing MATLAB 2018b (see instructions on final pages of
notes) and then downloading a toolbox available at
bit.ly/SimulinkOnRamp
OR
https://uk.mathworks.com/matlabcentral/fileexchange/69056-simulink-onramp
Once installed, restart MATLAB, launch Simulink and click the link under Learn…..
Explore Simulink Examples Use the Examples Tab to explore different Simulink models ( File > New > Model…)
There is even a bouncing ball example so you can see a different approach to one you might have taken in the final exercise.
Experiment with Simulink Dashboard Blocks Open the Fuel System Demo with the command:
open_system([matlabroot '\toolbox\simulink\simdemos\automotive\fuelsys\sldemo_fuelsys'])
Read through the documentation, so that you understand how the model works:
https://uk.mathworks.com/help/simulink/ug/tune-and-visualize-your-model-with-dashboard-blocks.html
Explore the blocks by double clicking them to get a better understanding of how they work.
Follow the instructions in the section Tune Parameters During Simulation to try editing the model.
Conclusion:
SIMULINK is a very powerful block diagram simulation language. Simple simulations, including the
majority of those used as examples in this textbook, can be set-up rapidly (in a matter of minutes).
The goal of this module was to provide enough of an introduction to get you started on the
development of open- and closed-loop simulations. With experience, the development of these
simulations will become second-nature. It is recommended that you perform the simulations shown
in this module, as well as the practice exercises, to rapidly acquire these simulation skills.
Conclusion:
Simulink blocks have zero, one or more inputs and zero, one or more outputs
Inputs & outputs are all considered “signals”
Unlike circuit-oriented simulators (e.g. Spice), Simulink has no knowledge of whether a signal is voltage,
current, power, torque, speed, …,
Simulink model and MATLAB Figure windows include a “Copy” function in the “Edit” menu. This is useful
for reporting results: you can simply copy and paste your models or graphical results into a Word or
PowerPoint document
You may want to explore other options in the MATLAB Figure window. For example, find out how add a
grid, change the line type, thickness or color, change the x-axis or y-axis scales, etc.
This tutorial is very limited in scope, just to get you started with the tools we will be using to model and test
various electrical or electro-mechanical energy systems in ECEN2060. You may want to browse through
SIMULINK/MATLAB HELP documentation to further explore the tool capabilities
References:
1. http://www.rpi.edu/dept/chem-eng/WWW/faculty/bequette/simulink.pdf
2. https://pdfs.semanticscholar.org/d4c1/193dedb3dc8057ca9f27517780095f31c26a.pdf
3. http://www2.eng.ox.ac.uk/~labejp/Seminar/Simulink/Simulink_Introduction.pdf
HAVE ANY QUESTION?????