When you are new to something, it always helps to get a
mental picture of how that something works. Since I learned Simulink over 10
years ago, I have developed my own mental model of Simulink models. Today I
want to present a mental model for the three basic components in Simulink block
diagrams, ports, blocks and signals.
Something Familiar
A good mental model is something to which you are already
familiar. I like to compare Simulink diagrams to programs written in a
procedural language like MATLAB or C. My favorite is MATLAB, so that is
usually how I think.
Ports
Ports are the input and output arguments for the function.
Blocks
When I think about blocks, I think of them as algorithmic
components of the programs. A block like the Gain or Product is a function
that operates on inputs and produces an output.
Signals
Signal lines pass the value output from one block to the
next block. I think of signal lines as the variables in a program.
Generating Code
With my intuition in hand, I read the generated code so I
can compare and refine my mental model. The result is here:
In this case, I made a couple tweaks to the code generation
settings for readability and interface.
What do you think?
How does your mental model of a block diagram compare to
mine? Leave a comment
here and share it with me.
Many people talk about the anticipation of the next iPhone, Kindle or some must-have techno gadget. I am looking forward to the next release of MATLAB. I downloaded the prerelease last week and now I am evaluating the new Simulink modeling features.
Currently licensed users can log in to their MathWorks account and see this:
The prerelease is a great opportunity to get a sneak peak at the new capabilities in MATLAB and Simulink. You can evaluate the new features and decide if it is time to pressure your team to upgrade when R2009b becomes available this fall.
If you have a base of existing models and code, this is a great chance to try it against the next release. If something doesn't work, contact technical support. This is an important mechanism to ensure compatibility, and your feedback is important.
Hi All
I would be highly obliged, if someone can show me a route to model a typical
2-to-1 Multiplexer, the way we have read & understood it. I want to
translate behavior of typical digital 2-to-1 Mux works like this into SIMULINK
model.
if(sel==0)
out = in1;
elseif (sel==1)
out = in2;
Today I want to look at one way to solve this question.
Controlling which signal passes through (Switch)
One way to think about this problem is to control which
signal gets passed through the system. The switch block provides a way to pass
through one signal or another based on the value of a control signal.
This creates an if-expression: when the conditional
statement is true, out is set equal to the first inport, otherwise, out is set
equal to the third inport.
Optimizing the model
This represents the desired logic, but there is another way
to think about the problem. Consider that both in1 and in2 are
the result of some other expensive calculations. When this is the case, you
will want to perform only one of the calculations needed for your output
expression instead of always computing both values and then discarding the one
that isn’t needed.
Luckily, this is a common pattern and Simulink provides an
optimization to improve efficiency. By default, Conditional input branch
execution is turned On (in the Configuration Parameters ->
Optimization page).
This optimization allows Simulink to group the upstream
blocks together and tuck them into the conditional statement of the Switch
block. You may be able to understand the behavior if you turn on the block
sorted order display, but I prefer to look at the code for simple models like
this.
This optimization is not just limited to the Switch blocks.
Other blocks that produce conditional expressions can incorporate upstream and
downstream blocks in their code.
I want to end this discussion with two important notes.
I made up this example specifically to demonstrate the effect of this optimization.
Because it is so simple, I had to disable Expression Folding, or else the code
would be the same, no matter what. I do not encourage anyone disable
expression folding without good reason.
Because this is an optimization, you cannot guarantee this behavior. If you add
something as simple as a Test point between the Gain and Switch Block
this will disable the optimization.
There are other ways to model efficient conditional behavior
and explicitly guard the execution of an algorithm. I will leave that topic for
a future post.
Now it’s your turn
Do you think about the efficiency of your models? How do
you use the Switch block? Leave a comment here and
share what you know.
As you may know, Space Shuttle Atlantis is about to
return this weekend from man’s last visit to the Hubble Telescope. Those
astronauts took some major risks to repair our favorite and most famous scientific
instrument. One of the tools they used during space walks is the robotic
manipulator from the Canadian Space Agency (the robotic arm).
Image Credit: NASA
I have never had a chance to operate a CSA robotic arm,
but my colleague Guy Rouleau has! Guy told me about a Simulink S-function he
created to help in controlling a robotic arm in Simulink.
Changing the color of blocks during simulation
By Guy Rouleau
I have many good memories from my internship at the
Canadian Space Agency when I was studying for my bachelor degree. During this
internship, I was developing control logic for a robotic arm. Simulink was used
to develop the controllers and as a user interface to command the robot.
When driving a robotic arm simulation using a joystick,
it is not always easy to visualize if you are close to a joint limit or a
singularity. It is possible to display the state values in the model, but hard
to know if you are about to lock out control of the arm. To help the person
driving the robot, we though it might be cool to make blocks in the Simulink
diagram turn red when close to a limit. This is what it looks like in action with
the SimMechanics mech_robot_vr.mdl model.
Here is a quick explanation of how to changing the color
of a block with a simple Level 2 M-file S-Function.
As a template, I suggest starting with the demo M-file msfcn_times_two.m.
In your MATLAB installation, you can open this file using the following
command:
>> edit msfcn_times_two.m
Only a few modifications are required to make the file change
the color of a block based on the value of the signal connected to the
s-function.
To begin, save the file as ChangeColor.mfor
this example. At the minimum, you need to modify the code of the Output
section. To start, I created a model named “Test” where we will change the
color of the block named “Display”
The simplest implementation can look at the input value, and
then use set_param to modify the block BackgroundColor:
In the above code, the color of the block “Test/Display”
is set to green or red depending if the input is larger or smaller than zero.
In order to make the code reusable, I may want to determine
automatically which block is connected to the S-Function. We can also add a
parameter to the block to set the value at which the color switches. In that
case, we add these lines to the setup function:
Notice that the handle to the destination block is stored
in the “UserData” of the S-function. UserData is often useful for storing any
data you need to persist with the S-function, but doesn’t fit the definition of
a continuous or discrete state. The output function now looks like:
Finally, if you want the block to return to white at the
end of the simulation, you can add these lines to the terminate function:
Do you work on a robotic arm or on the Hubble? Have you
used an S-function to customize what Simulink looks like? Share your
experience and leave a comment
here.
I stumbled upon a blog post over at The Green Garage where they interviewed a
couple of my colleagues, Paul Smith and Shaun Kalinowski. They talked to them
in front of the MathWorks booth at the SAE World Congress in Detroit. I have
embedded the video here in case you want to watch it now:
The focus of the interview is about answering the question
“How do you make math cool again for students these days?” MathWorks is an EcoCAR
sponsor, and Shaun is one of the mentors for an EcoCAR team. I really like Paul’s
comparison of engineering simulation to playing video games while you are doing
your work.
About thirty seconds into the video Paul describes
Model-Based Design as “a technique used by engineers to design the next
generation of systems that go into cars, airplanes and cell phones.” I have
had many conversations with people who say they are doing Model-Based
Design. Are they all using the same technique? How do you define and
document what that technique is?
I think this line of questioning leads to an interesting
observation. Model-Based Design means different things to different people,
and there is no one right way to do it. The MathWorks website has some great
user stories about applying Model-Based Design techniques. These storied
include companies like Boeing,
Astrium,
Bell
Helicopter, BAE
Systems, Toyota,
and Xerox.
Each of these user stories tells of the specific benefits that group received from
applying Model-Based Design.
Now I ask the following question:
What does Model-Based Design mean to you?
If you are using Model-Based Design, how are you doing
it? What is the most important benefit?
Please leave comments on this
blog post, or if you want to be a guest blogger and write something a little
longer, e-mail me directly.
While browsing through the file exchange,
I clicked on the Simulink
tag to see the latest Simulink files. Saurabh’s demo of how to customize
the Simulink interface was right at the top. You can really appreciate what is
in this submission without even downloading it. The ZIP file contains a published
M-file that documents and explains each customization in detail. (Everyone
should do this!)
Saurabh explains how to make a few key customizations to
the Simulink interface.
Reordering Libraries in Simulink Library Browser.
If you don’t like the default order of libraries
(alphabetical, with Simulink always on top), you can reorder them. This is
particularly helpful if you use a pallet library to keep you custom blocks on
hand. (I have previously blogged about adding
custom libraries.)
Disabling and Hiding Libraries in Simulink Library
Browser.
Why would you ever want to do this? Well, I most often hear
the request from larger teams that need to restrict the blocks allowed in their
design. If your team doesn’t allow continuous blocks in their controller
model, it might be easier to keep them out of sight and prevent their insertion
from the start.
Customizing Simulink Menus.
The example here is very simple, but I have used this one
myself. I made a custom menu that would generate a bus object for the
currently selected port or bus creator. This saved me the time of having to
type Simulink.Bus.createObject('model', 'model/Bus
Creator').
Disabling and Hiding Options in Configuration Parameters
Dialog.
Just about every menu and configuration parameter can be
enabled/disabled and hidden. This flexibility helps when enforcing team
modeling styles and preventing common errors because of mistaken settings.
Now it’s your turn
I hope you will download the
file, rate it, and leave comments. How do you use customizations? Leave
me a comment here,
or submit your own customizations to the file exchange!
This almost never happens, but today I get to share with you
an undocumented Simulink capability! In R2009a the S-function builder
has the ability to accept bus signals at its input and output ports. We accidentally
omitted the updated doc section when R2009a shipped. You can find the missing
documentation here, but I still want to tell you about how to use bus
signals with S-function Builder.
What is an S-function?
If you want to build your own custom block in Simulink, we
provide a couple ways to do it. For now, I am going to ignoring masked
subsystems and reference models and focus on block authoring in the truest
sense, the S-function. The "S" in S-function stands for System (or
maybe Simulink). S-functions define how a block works during the different
parts of the simulation, for example: initialization, update, derivatives,
outputs, and termination. S-function are often used as a gateway to other
simulation environments, interfaces to hardware or software. There are a few
ways to implement
an S-function, such as using an M-file or a C-MEX file. There are also
tools like the S-function
Builder Block and the Legacy
Code Tool to make it easier to write S-functions.
The S-function must define itself as a system. You have to
define the interfaces and algorithm for the system. The interfaces to the
system are the ports and parameters of the block. For a long time, users have
asked for the ability to write an S-function that accepts a bus signal as the
input, or provides a bus signal as the output. This is the capability added in
R2009a for the S-function Builder.
S-functions and Bus Signals
In January 2005, Tom
Erkkinen posted the Legacy Code Tool (LCT) to the MATLAB Central File
Exchange. The Legacy Code Tool helps you integrate
existing C functions into your Simulink model by generating an S-function.
LCT has been shipping with Simulink since R2006b. One of the major
capabilities of LCT is the ability to interface to bus signals. If your
function requires a structure input or returns a structure output, LCT can
generate the wrapper S-function that handles a bus signal.
S-function Builder Bus Support
I think the S-function Builder block is the easiest way to
bring a short C code algorithm into your Simulink model. New in R2009a, the S-function
Builder block now supports bus signals for the input and output ports. There
is a demo model called sfbuilder_bususage. Here is how it works:
The S-function builder works like many software wizards, and
leads you through the process of writing an S-function. When you double click
on the S-function builder block, you get a GUI that looks like this.
If you start on the left most tab, add information in each
tab, by the time you have reach the last tab, you are done. To include a bus
input in the S-function builder, you need to define a bus object. In a
previous post, I talked about how to do use bus
objects as interface specifications. The Data Properties tab defines all
the information for the ports of the S-function. First, you have to define the
inputs and outputs of your system.
To include a bus, turn the Bus property ON, and se the Bus
Name to the bus object in the base workspace. Next, you have to access
elements of the bus using standard C structure indexing. Here is a snippet
from Outputs function that accesses signals from the bus.
That is all there is to it. The bus object can optionally include
a C header file that defines the C structure definition for the bus. You can
specify this in the Bus Editor:
If you include the header file in your bus object, the S-function
builder will use it. If you don’t specify the header file, the S-function
builder will generate one for you that looks like this:
Wait a second, why isn’t this in the doc?
It was just an oversight. There were many changes made to
the doc, and we forgot to include this one. Luckily, when we realized the doc
was not complete, technical support came to the rescue. We have published a
revised section of the S-function builder documentation through a solution
titled:
The Spring MATLAB programming contest has just begun. This contest is different from contests in the past, so I recommend you start by reading the contest rules. This contest is less about algorithms and tweaking (although I'm sure that will happen), and more about visualizing an interesting data set. The data set for this contest is previous contest data! I took a crack at it and submitted my own visualization.
I wanted to look at the underlying space of two factors that went into the overall score for the contest, and see how they
related to the length of the entry. The main factors that affect score are the result, complexity and the CPU time. I chose result, cpu_time
and the nodeCount for my visualization. This is perfect for a 3-D scatter.
Here is the result of my visualization, animated to get the full 3-D effect.
Have you seen the MATLAB
Channel on YouTube?? I like the way you can express an idea using video, describe
how things work, and then watch it work. That is why I asked my friend Doug to
help me make a video this week. (Thanks Doug! Check out Doug’s MATLAB Video Tutorials.)
The topic today is the Simulink R2009a feature for Parallel
Model Reference builds. Model reference blocks run in normal (interpreted)
mode or accelerated mode. Simulink has to generate SimTargets for the
accelerated reference models during update diagram. In R2009a you can use the
Parallel Computing Toolbox to start a pool of local MATLAB workers and
distribute the generation of the SimTargets across the available cores on your
system. Model Reference parallel build also speeds up Real-Time Workshop code
generation. All you need to distribute your build across all the cores on your
multi-core machine is to start a local pool of MATLAB workers:
>> matlabpool
Starting matlabpool using the 'local' configuration ...
connected to 4 labs.
Watch the video. Try it out. Leave a comment below and
tell me how it worked.
Updated the video player which was broken on IE.
Files used in this video are available from the File Exchange here
I am so excited about
saving and restoring the simulation state in Simulink. This is
my favorite feature of R2009a because it has been long anticipated
and it enables important new capabilities for simulations. While the
only interface change was the addition of a check box under Data
Import/Export in the configuration parameters, this has affected
every block that stores some kind of state information, including
Stateflow. Who better to explain this than the developer who has spent the last
couple of years enhancing Simulink to save the entire simulation state? In
this post, I present guest blogger
Zhi Han.
What is the state of my last simulation?
By Zhi Han
The capability for saving and restoring the state of simulation has
been one of the long-standing requests from users of Simulink. The
motivation comes two-fold. Sometimes simulation takes a very long time,
and often it is desirable to break a long simulation into several stages.
In addition, if you simulate a model many times, most of the simulations
share a common phase such as the start-up of the system. In these cases,
it is desirable to save the state of the system at the end of the
simulation and restart a simulation later from that saved state.
Prior to R2009a, Simulink provides the ability to save the final state
and load the initial state of a model. However, Simulink could only loads
the logged states. Logged states are continuous state and discrete work
vectors used as state, which is only a subset of the variables used in
simulation. In real-life models, the set of logged state is often not
enough to capture the complete state of simulation.
As an experiment, let us open a Simulink demo model
sldemo_VariableTransportDelay. The model uses Variable Transport Delay blocks
to capture the delay between the vertical displacement of the front wheel and
rear wheel of a running car.
Models with Transport Delay blocks are usually difficult to restore to
their state because, when you save the "Final states", Simulink does not
save the state of the transport delay in the structure format or the array
format. As a demonstration, we simulate the model from 0 to 5 seconds and
save the "Final states" in structure format in the workspace. Then we load
this saved state and simulate from 5 to 10 seconds.
The blue
lines are the results of a nonstop simulation, which serves as our baseline. The
red dashed lines are the results of our experiment. It can be seen that beginning
from 5 seconds on the restored simulation does not match the nonstop
simulation.
In R2009a
Simulink introduces the feature to
save
and restore the complete set of states
used in simulation; this is the SimState of the model. By
saving the SimState at the end of a simulation, Simulink is able to
restore all the simulation variables as they were and reproduce the exact
same simulation results as a nonstop simulation.
Now, we check the box and repeat our experiment. By restoring the
complete simulation state, the saved and restored simulation results
match the nonstop simulation.
Here are some important features of the SimState:
Timing information
The
SimState retains the timing information of the model of the last simulation,
including the start time and the current simulation time: the last time that
the simulation runs. Upon restoration, Simulink restores both the start
time and the simulation time. This is very important to handle correctly
time-varying systems. This detail of the SimState has the following
effects that may surprise the user:
The start time specified in the restored simulation, if different
from the start time of the last simulation, overrides with the start
time stored in the SimState.
When loading a SimState, the user must make sure the stop time
is greater than the last simulation time; otherwise, Simulink
immediately stops the simulation after loading the SimState to the model.
Structural changes
Simulink checks the structure and the configuration parameters of the
model with the information stored in the SimState to verify that the model
has not changed before loading the SimState. Structural changes, such as
adding or deleting a block, renaming a block, or changing the connection
between blocks would make the model incompatible with the SimState.
Accessing the states
The data stored in the SimState is accessible to the user. You can
change the values saved in SimState to initialize the model to a
different operating point than the last simulation. For the logged
states, the values are available in structure format as
xFinal.loggedStates. For a Stateflow chart, the state is
available using the following:
>> state = xFinal.getBlockSimState('path_to_the_Stateflow_Chart')
To set the state of a Stateflow chart, use the following function.
>> state = xFinal.setBlockSimState('path_to_the_Stateflow_Chart',x)
Check out the SimState
documentation for the full details on how this new capability works.
Now it's your turn
Do you initialize simulations with the state from a previous run? Did you
request this capability? Leave a
comment here
and tell us what you think.
Recent Comments