Seth on Simulink

June 26th, 2009

My Mental Model of a Model

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.

A Simulink block diagram and corresponding M-code to illustrate my mental model.

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:

The generated code from the model.  Pretty close to the mental model.

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.

June 18th, 2009

Sneak Peak At The Next Release!

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:

MathWorks account page announcing the R2009b Prerelease.

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.

June 2nd, 2009

The If-Else Construct in Models

Balaji Kalluri asked a question in the comments of a post about the MUX block.  Balaji asked:

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.

Model of conditional pass through using a switch.

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

Conditional Input Branch Execution optimization from Simulink configuration parameters. 

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.

Comparison of generated code with and without conditional input branch execution optimization.

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.

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

May 22nd, 2009

Robotic Arm Models and Repairing Hubble

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 Source: Nasa - STS125 Hubble above the space shuttle Atlantis cargo bay

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

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

Using a joystick to control inputs to a Simulink model of a robotic arm.

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.

Animation of a virtual reality robotic arm with red and green displays to indicate joint state.

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.m for 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”

Simulink test model to show the S-function working.

The simplest implementation can look at the input value, and then use set_param to modify the block BackgroundColor:

Outputs code for the S-function

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:

Block setup code

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:

Block outputs using User Data to get the block handle

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:

Terminate function that sets the block back to white background.

You can find this example in my File Exchange Submission: Changing the color of a block while the simulation runs.

Now it is your turn

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.

May 13th, 2009

What does Model-Based Design mean to you?

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.

April 29th, 2009

Pick of the week: Customizing Simulink

This week I am borrowing the Pick of the Week blog format pioneered by Scott and Doug and carried on by the three amigos: Bob, Brett and Jiro.

Simulink Pick of the Week

Seth’s pick this week is Customizing the Simulink Interface Demo by Saurabh Mahapatra

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

Customizing the Simulink Interface Demo on the MATLAB Central File Exhcange

Saurabh explains how to make a few key customizations to the Simulink interface.

Reordering Libraries in Simulink Library Browser.

Reordered libraries in the 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.

Hidden libraries and disabled libraries in Simulink

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.

Custom menus added to Simulink

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.

Disabling and hiding stuff in the configuration prarameters

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!

April 17th, 2009

S-functions, Bus Signals, and Missing Documentation

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 Simulink S-function Builder Block in the library browser

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.

The S-function builder GUI

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.

The S-function builder with a bus input

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.

C-code from the Outputs Function that accesses bus signal elements

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:

The Bus Editor can be used to specify the headerfile for the bus

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:

The S-function Builder generates a header file for your bus if you don't provide one in the bus object

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:

How can I input and output Bus signals to and from an S-function created using the S-function builder in Simulink 7.3 (R2009a)?

Now it’s your turn

Do you write S-functions?  Have you tried this feature?  Leave a comment here and tell me about your experience.

April 1st, 2009

Spring 2009 MATLAB Contest: Data Visualization

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.

Take a look at Doug's contest blog post for other ideas on how to visualize this data.

March 31st, 2009

Parallel Computing with Simulink: Model Reference Builds

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

March 20th, 2009

My Favorite New Feature in R2009a: SimState

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

Simulink developer 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.


Seth Popinchalk is an Application Engineer for The MathWorks. He writes here about Simulink and other MathWorks tools used in Model-Based Design.
  • Jarrod Rivituso: “I think of signal lines as the variables in a program.” I say the exact same thing...
  • actuator: This is very impressive. Thanks for sharing
  • Guy: @Pat and Paul, I agree that the slblocks documentation is unexisting. From what I remember, when subsystems are...
  • Jeff: Hi Seth, Thanks for the feedback. I actually decided to go with the second option since it made more sense for...
  • javadaein: unfortunately mathworks can not be accessed in iran. I dont know why mathworks guys do that but I...
  • Pat: Dear Paul, I am facing the same problem, were you able to solve it!? Pat
  • Seth: @Syed Murtuza Hussain - Happy to provide some inspiration. @Rienzi Mosqueda - The example models I would share...
  • Seth: @Jeff - Regarding your first question about handling a bus with a Level 2 M-file S-function: you are correct,...
  • M.tamilselvan: this piece of snippet is short and crisp,need to post more mental model strutures in depth possible...
  • rienzi mosqueda: hi.!im currently into the studying a robotic arm and possibly simulating one by controlling it by a...

These postings are the author's and don't necessarily represent the opinions of The MathWorks.