Seth on Simulink

February 4th, 2010

New (Since R2009a) Simulink inside Stateflow

This week I asked Michael Carone to introduce a relatively new Stateflow capability, Simulink Functions.

Stateflow expert Michael Carone

Did you ever want to put a Simulink block inside of a Stateflow chart?  Well, if you have R2009a or R2009b, you can!

Simulink subsystems inside Stateflow Charts.

When you open your Stateflow chart, you’ll see a new white button that looks like a Simulink subsystem on the bottom of the graphical palette.  Use that button to drag in a Simulink function (just like you would for an Embedded MATLAB function), double-click on the function, and you have a Simulink window for creating your new Simulink function.  Or if you have a function already built in Simulink that you want to embed in Stateflow, just copy and paste that block from Simulink into Stateflow (new for R2009b).

Now some of you might be asking, “Why would I want to do this?”  Well, there are a few applications that immediately come to my mind.  Maybe you have an algorithm you already designed in Simulink that you want to reuse in Stateflow.  Or maybe you want to use Stateflow to schedule exactly when to trigger a specific task or controller.  You might also want to control the behavior of separate components modeled in Simulink. 

Check out this MATLAB Digest article if you want to see some design patterns for using Simulink functions in Stateflow.  There’s also a simple demo here you can check out.  Or go to the documentation if you really want to get all the details.

Now it’s Your Turn

Can you see how embedding Simulink functions in Stateflow charts would be helpful for your models?  Leave a comment below and let me know.

January 29th, 2010

Recent Grads Wanted for Jobs at MathWorks!

I don’t normally host gratuitous advertisements for MathWorks events, but this one is an uncommon opportunity.  MathWorks is hosting a virtual career fair next week, February 4th from 11 AM to 7 PM (Eastern time).  While I wouldn’t normally recommend you show up for a job interview in your pajamas, this time it won’t matter.  Register now!

MathWorks Virtual Career Fair

Do you love MATLAB and Simulink? Are you the smartest person in your class?

The MathWorks offers career opportunities for CS, EE, and ME students and new graduates with MATLAB programming skills.

  • Live chats with recent graduates and hiring managers
  • Presentation with question-and-answer session
  • Exhibit floor with virtual booths hosted by MathWorks technical staff

Chat with MathWorkers in virtual conference booths.

Register now!

January 21st, 2010

Building Models with MATLAB Code

Occasionally I get questions about how to build, modify, and add blocks, to Simulink models using MATLAB commands. In this post, I will to give a basic overview of the common model construction commands.

Contents

Start With a New System

Because you need to refer to the system so often when doing model construction from M-code, I immediately save that off in a variable called sys. The new_system command created the empty model in memory, and you have to call open_system to display it on-screen.

sys = 'testModel';
new_system(sys) % Create the model
open_system(sys) % Open the model

Adding Blocks and Lines

When I add blocks to the canvas, I specify the position to provide proper layout. The position parameter provides the top left (x,y) and lower right (x+w,y+h) corners of the block. The x and y values are relative to the origin (0,0) in the upper left corner of the canvas; x increases to the right, and y increases down. To keep my layout organized, I use a standard blocks size of 30 by 30, and offsets of 60.

x = 30;
y = 30;
w = 30;
h = 30;
offset = 60;

I like my ports with slightly different proportions, so I define them to be half the height of the other blocks. add_block specifies the source block and the destination path, which defines the block name. Block names must be unique for a given system so add_block provides a MakeNameUnique option. (not used here)

pos = [x y+h/4 x+w y+h*.75];
add_block('built-in/Inport',[sys '/In1'],'Position',pos);

I'll add an integrator block, offset to the right of the inport.

pos = [(x+offset) y (x+offset)+w y+h];
add_block('built-in/Integrator',[sys '/Int1'],'Position',pos)

To connect the blocks, call add_line and provide the system name, source port and destination port. The ports are designated by the 'blockname/PortNum' format. Default line routing is a direct line connection from the source to destination. I prefer to use the autorouting option.

add_line(sys,'In1/1','Int1/1','autorouting','on')

When adding multiple blocks and lines, I group them into add_block/add_line pairs to keep myself organized.

pos = [(x+offset*2) y (x+offset*2)+w y+h];
add_block('built-in/Integrator',[sys '/Int2'],'Position',pos)
add_line(sys,'Int1/1','Int2/1','autorouting','on')

pos = [(x+offset*2) y+offset (x+offset*2)+w (y+offset)+h];
add_block('built-in/Scope',[sys '/Scope1'],'Position',pos)
add_line(sys,'Int1/1','Scope1/1','autorouting','on')

Deleting Blocks and Lines

When deleting blocks, I call delete_line before delete_block. This is the reverse of what I did before. The commands are grouped in delete_line/delete_block pairs. For this example, I'll delete the integrator Int2, and add an outport.

delete_line(sys,'Int1/1','Int2/1')
delete_block([sys '/Int2'])

pos = [(x+offset*2) y+h/4 (x+offset*2)+w y+h*.75];
add_block('built-in/Outport',[sys '/Out1'],'Position',pos)
add_line(sys,'Int1/1','Out1/1')

Replacing Blocks

Sometimes you don't really want to delete a block, you are just going to replace it. replace_block gives you the capability to replace all blocks that match a specific criteria. I reccommend carefully reading the documentation to better understand this function.

replace_block(sys,'Name','In1','built-in/Sin','noprompt');
set_param([sys '/In1'],'Position',[x y x+w y+h],'Name','Sine Wave');

[t,x,y] = sim(sys);
plot(t,y), ylim([-.5 2.5]), grid on

Now it's your turn

Do you use model construction commands? Why doesn't the cosine on that scope cross below zero? Leave a comment here with your thoughts.


Get the MATLAB code

Published with MATLAB® 7.9

January 7th, 2010

PID Control Made Easy - Part 2

Happy New Year! Many people like to make resolutions at this time of year. They often take on ambitious and even difficult resolutions to accomplish some far off goal in 2010. Instead of doing something difficult, how about a resolution to make something easier?

Arkadiy Turevskiy previously presented an overview of the new blocks and tuning tools for PID controllers in R2009b. While I think his post accurately shows the details of how the PID tuning tools work, unless you do it yourself, it is hard to appreciate how easy it really is. Luckily, Arkadiy also recorded a short video to go with his post. While you watch the video, notice that he gets a proposed controller design with one click, applies it with a second click, and adjusts the response time using a slider in the tuning GUI.

Now that's easy

What are you resolving to do this year? What tool will you use to make life easier? Tell us about it in a comment here.

December 24th, 2009

PID Control Made Easy

Today I introduce guest blogger Arkadiy Turevskiy to share some new features in R2009b: the PID Controller Blocks in Simulink and a new PID tuning method in Simulink Control Design.

PID Gain Tuner Arkadiy Turevskiy

PID (Proportional-Integral-Derivative) control seems easy: you just need to find three numbers: proportional, integral, and derivative gains. Many PID tuning rules exist out there and all you need to do is pick up one and press a button on a calculator. Easy enough, right? Unfortunately, the story is more complicated than that. Popular PID tuning methods are restrictive. For example, to use one of the most popular methods - Ziegler-Nichols - you need a stable, first order plus dead-time linear time-invariant (LTI) plant model. Even if your model is of that type, the method does not support tuning of integral or proportional-derivative controllers, and for the types of PID controllers it supports, it only provides one answer with no easy way to fine-tune the design. Moreover, tuning is not the only challenge. Real-life PID implementation also needs to consider such issues as output saturation, integrator wind-up, and discrete-time implementation.

In R2009b we released new blocks in Simulink and a new PID tuning method in Simulink Control Design that together address these challenges. To see how this works, let’s consider an example of designing a PID controller for a dc motor. The model of a closed loop system uses the new PID Controller block. This block generates a voltage signal driving the dc motor to track desired shaft rotation speed. In addition to voltage, the dc motor subsystem takes torque disturbance as an input, allowing us to simulate how well the controller rejects disturbances. We also modeled analog sensor noise in the speed measurement.

DCMotor Model with a PID compensator

The PID controller is a discrete-time controller running at 0.02 seconds (the red color shows the sampling time in the model). Let’s now look at the dialog of the PID Controller block. In the upper half of the dialog we specified basic configuration of the PID controller: type (PID, PI, PD, P, or I), time-domain, integration methods, and sample time. In the lower part, we specified PID controller form and gains (shown at default values).  Block documentation provides detailed information about the block and all its parameters.

PID Controler Block Dialog

PID Tuning

Our first task is to tune the PID controller. Pressing the “Tune…” button in the PID Controller block dialog, we launch PID Tuner, which linearizes the model at the default operating point and automatically determines PID controller gains to achieve reasonable performance and robustness based on linearized plant model.

PID Tuner Interface

The grey line shows the system step response for the gain values currently defined in the block dialog, and the blue line shows the system response for the gain values that PID Tuner proposes. We can simply accept the proposed design and then run our closed-loop Simulink model to check the results. In the simulation, we command a step change from 0 to 2 rpm at 1 second and a step down to -2 rpm at 7 seconds. Results demonstrate good tracking with zero steady-state error, fast rise time, low overshoot, and good torque disturbance rejection (torque disturbance is modeled as a step change from 0 to 0.2 Newton-meters at 5 seconds). The tuning algorithm we just used works on any type of plant model, tunes all forms of PID controllers that can be specified in the PID Controller block, and takes sampling effects into account during the tuning process.

Scope showing a voltage disturbance

If system response does not meet our requirements, we could further fine-tune the design by interactively making the controller faster or slower, using the slider on the bottom of the PID Tuner GUI.

Integrator Anti-Windup Protection

We now run a different scenario, assuming no torque disturbance and assuming that the amplitude of voltage fed to the dc motor cannot exceed 10 Volts – to protect the motor from overheating. We use the “PID Advanced” tab of the PID Controller block dialog to specify these saturation limits.

Advanced Tab from the PID Controller Block Dialog

Measured speed scope showing integrator wind-up

We see that at the time of the first step change at 1 second, voltage signal from the controller saturates at 10 Volts.  When desired speed drops at 7 seconds, the voltage does not decrease immediately and stays at 10 Volts for almost 2 more seconds.  This is the result of integrator wind-up in PID controller, which leads to undesired delay in tracking the speed command.  It can be fixed by enabling integrator anti-windup in the PID Controller block dialog. Rerunning the simulation with integrator anti-windup enabled, we see that the controller still cannot achive commanded speed value of 2 rpms –it simply does not have enough authority, but when the speed is commanded to -2 rpms, controller quickly responds to change in the requested speed.

Scope showing effect of turning on anti wind-up

As we saw, the new PID tuning method and the new PID Controller block helped us quickly tune our PID Controller, and create a discrete-time design that addresses output saturation and integrator wind-up issues.

Now it is your turn

Do you use PID control? How do you address integrator wind-up?  Leave a comment here and tell us how you tune your controller gains.

December 14th, 2009

Round-off Error

Loren recently posted a simple example of how single-threaded computations might produce different results from multi-threaded computations.  The cause is floating-point round off, and most people are surprised to learn that the "different" results actually agree!  In this post, I want to explore this same example in Simulink.

Order of Operations is Important

Loren’s example shows that the answer you get from the following equation depends on the order that you perform the operations:

1e-16 + 1e-16 + 1e30 - 1e30

Here is the same equation expressed in Simulink blocks.  The model doesn’t explicitly specify the order of operations, so they are done from first to last input (top to bottom, ie ((1e-16 + 1e-16) + 1e30) - 1e30). 

Simulink model adding 4 values with a single rectangular sum block

Here is the same equation with a different parenthetical grouping, where the inputs to each operator are signals of the same magnitude.

(1e-16 + 1e-16) + (1e30 - 1e30)

Simulink model adding values of similar magnitude with 3 sum blocks

In another grouping, the inputs to the operators have very different magnitudes.

(1e-16 + 1e30) + (1e-16 - 1e30)

Simulink model adding values of very different magnitudes

I like these examples because they show how floating point round off affects the result.  An important aspect of these calculations to consider is the spacing between floating-point numbers of a certain magnitude.  The EPS command gives you the difference between a number and the next floating-point precision number.  What is EPS for 1e30?

>> eps(1e30)
ans =
  1.4074e+014

Considering that the spacing of floating-point numbers around 1e30 is MUCH larger than 1e-16, you can why there is sensitivity to the order of these operations.  For any normal floating-point number X, you can expect no difference in the result if you add less than half EPS(X).

>> 1e30 + 7e13 == 1e30
ans =
     1
>> 1e30 + 8e13 == 1e30
ans =
     0

How could this really affect me?

Imagine a model where precision in the results is a critical consideration.  Choices made about the units of parameters, and the order of operations could have an impact on precision of the calculation, especially if working with a more compact number representation like single precision floating-point.

Now it’s your turn

Have you ever run into a strange result only to find out it was within the bound of floating-point error?  Share your experience with us in a comment here.

December 2nd, 2009

Floating-Point Numbers

Numeric simulation is all about the numbers.  In a previous post, I talked about integer and fixed-point number representations.  These numbers are especially useful for discrete simulation and embedded systems.  For continuous dynamic systems, the values do not represent discrete values but continuously changing functions in time.  For this, floating-point numbers provide the flexibility and range of representation needed to store results.  In this post, I will review the fundamentals related to floating-point numbers.

Sign, Exponent, Fraction

Floating-point numbers extend the idea of a fixed-point number by defining an exponent.  A normalized floating-point number has a sign bit, the exponent, and the fraction.

sign

exponent (e)

fraction (f)

The fraction can represent numbers where 0≤X<1. The exponent provides the ability to scale the range of the numbers represented by the fraction.  The spacing of floating-point numbers is relative to the number of fractional bits and the magnitude of the number represented.  For very large values of the exponent, the spacing between the numbers is large.   For small numbers, the spacing is small.  This space between the numbers you can represent in floating point is called epsilon, or eps.  When calculations result in a number that falls into one of these spaces between floating-point representations, rounding occurs.  This rounding introduces an error to the calculation on the order of eps.

Cleve Moler wrote a great article titled Floating Points.  It gives a great explanation of how floating point works and some of the historical context for the IEEE double precision standard.  In the article, he describes a toy floating-point system consisting of one sign bit, a three-bit exponent, and a three-bit fraction.

sign

exponent (e)

fraction (f)

+/-

+/-

21

20

2-1

2-2

2-3

The exponent can hold integer values between -4 and 3.  The fraction holds values of 0 to ⅞ with a ⅛ spacing.  The value of a normalized floating-point number is:

x = ± (1 + f ) × 2e

The following graphic from Cleve’s article illustrates the spacing between floating point numbers in this toy system.

A toy floating point number system showing the spacing between numbers. 

This is my mental image when I think about floating-point numbers and issues of precision in floating point calculations.

Resources

There are many great sources of knowledge about floating-point numbers on the web and everyone seems to have a favorite reference.  My favorite is from Cleve, but here are some more resources to check out for yourself.

Floating Points by Cleve Moler

What Every Computer Scientist Should Know About Floating-Point Arithmetic by David Goldbeg

Where Did All My Decimals Go? by Chuck Allison

Now it’s your turn

Can you think of an example of an embedded system that needs to represent numbers over a full range from 2.2251e-308 to 1.7977e+308?  What resource do you turn to when you have questions about floating-point numbers?  Leave a comment here and share it.

November 18th, 2009

Back-Seat Driver: Simulink Tips for Efficient Model Navigation

Does this ever happen to you? You are sitting in a meeting looking up at the projected image of your coworker’s computer desktop.  They are navigating through {a web page, a Simulink model, or computer settings}.  You can see a faster, better, more efficient way to complete the task.  You as the observer have two options:  1) politely bite your lip or 2) become the back-seat driver and scream out corrective commands like “up, up, up... to the right, right, left... click the thing...open... control-k...arg!”

This happens to me some times... especially with Simulink models.  I want to share with you two Simulink tips that I wish everyone knew.

Tip: Navigating your model – window reuse, and escape.

I spend much of my day looking at models I did not build.  Finding your way around large models can be slow due to the many layers of subsystems between the top of the model and the leaf component you are working on.  There are two parts to this tip.

Part one is setting window reuse.  Make sure the model is set for window reuse.  I rarely need to look at two different systems at the same time, so my preference is to set Simulink to reuse the windows as I navigate the diagram.  A close alternative is to use mixed.

Simulink Preferences control window reuse.

Part two is using the escape key.  Diving down through layers of a model is as easy as double clicking on a subsystem.  What do you do when you want to go back up a level?  While you can reach for the arrows on the toolbar to go back, or up a level, I use the escape key.  Escape will bring you to the level above the current level.  This even works if you have opened a reference model, Stateflow chart, Embedded MATLAB function blocks and block dialogs!

Annimation showing the easy navigation accross many levels of model hierarchy.

What do you know?

What accelerators do you use to work more efficiently?  What do you yell when back-seat driving? Leave a comment here and tell me about it.

November 6th, 2009

Generated Code for Variable Size Signals

Aarti recently posted about Variable Size Signals in Simulink. Han responded with this comment:

Aarti,
I would be interested in the effect on RTW generated code for variable size signals. Could you show some examples?
-Han

Here is Aarti's response.

Aarti Ramani

Hi Han,

Thank you for your comment. In the case of a variable size signal, the generated code allocates the maximum possible size for the input/output variables.

This allows signal sizes to vary during execution (as opposed to being hard-coded after model compilation). The generated code also propagates signal sizes through the model and accordingly assign the required dimension to signals. The algorithm code only needs to operate on the portion of memory required (thus saving execution time).

The following model uses the Switch Block to change the size of its output signal.

Simulink model containing a Switch and Gain block that handles variable size signals.

The generated code looks like this:


  /* Switch: '/Switch' incorporates:
   *  Inport: '/In1'
   *  Inport: '/In2'
   *  Inport: '/In3'
   */
  if (In2 >= 0.0) {
    model_XDim = 1;
    X[0] = In1;
  } else {
    model_XDim = 5;
    for (tmp = 0; tmp < 5; tmp++) {
      X[tmp] = In3[tmp];
    }
  }

  /* Gain: '/Gain' */
  model_YDim = model_XDim;
  loop_ub = model_XDim - 1;
  for (tmp = 0; tmp <= loop_ub; tmp++) {
    Y[tmp] = 2.0 * X[tmp];
  }

In the generated code, notice how the variable model_Xdim has the lower and upper bound pre-allocated as 1 and 5, 5 being the width of the 3rd Inport block. Using these values, the loop_ub variable for the Switch block is calculated.

Thanks!

Aarti

Is this the code you expected? Leave a comment here and tell me about it.

October 28th, 2009

STEM Educational Initiative Signing, and Robotics Competitions

It is not every day that I attend a speech by political leaders of the Commonwealth of Massachusetts.

Governor Deval Patrick speeking about the STEM Advisory Council at the MathWorks
Governor Patrick speeking about the value of science technology engineering and math (STEM) education during his visit to The MathWorks on October 14, 2009. Photo by Jeff Newcum

On October 14th, 2009 Massachusetts Governor Deval Patrick signed an executive order to establish the Science Technology Engineering and Math (STEM) Advisory Council.  The MathWorks hosted the gathering of local political leaders.  MathWorks CEO Jack Little introduced the Lieutenant Governor Timothy Murray and the Governor Deval Patrick to a room filled with MathWorkers.  I could describe all the formalities and go into what this means for STEM education in Massachusetts, but other media sources covered those topics (like EDN, Mass High Tech and the Governors official website).  Instead I would like to focus on some of the tangents to the main event.

Governor Patrick signing the executive order to establish the STEM Advisory Council
Governor Patrick signing the executive order to establish the STEM Advisory Council. Photo by Jeff Newcum

Talking to the Governor

My fellow blogger, Loren Shure, asked Governor Patrick what he thinks good corporate citizens can do to support STEM education.

Loren Sure expressing her interests in STEM education to Governor Patrick
Loren Shure expressing her interests in STEM Education to the Governor. Photo by Jeff Newcum

The Governor gave a couple examples of how companies can get involved such as mentoring area students and engaging in student competitions.  There already exist many opportunities to do this…

Mentoring

I have known many MathWorkers who volunteer at a local elementary school as math tutors in preparation for standardized tests.  The same school has a Lego® Club where some of my colleagues mentor students on building robot using Lego® Mindstorms.

Competitions

In Governor Patrick’s response to Loren, he gave a specific example of a robotics competition, FIRST.

Most people have heard of FIRST (For Inspiration and Recognition of Science and Technology).  If you haven’t, browse around the FIRST website for a few minutes and get inspired about the great things available to the next generation of engineers and scientists.  They have programs targeted at many different age groups, from the Junior FIRST Lego League for ages 6-9 years all the way up to “the varsity sport for the mind” FIRST Robotics Competition for ages 14 to 18 years.

Targeted toward college students is the EcoCAR Challenge (which I wrote about in a recent post). MathWorks is a sponsor of the competition, and some of my colleagues act at mentors to teams. The goal is to modify GM donate vehicles in an attempt to reduce emissions, minimize fuel consumption AND maintain consumer appeal.  Those college students involved are already on their way to careers in engineering.

Another competition I am very excited about is ET Robocon, which MathWorks also sponsors.  The site is in Japanese, but you can see videos like this one on YouTube (search for ET Robocon).  I see ET Robocon as an embedded software design competition.  Teams all start with a standard LEGO® NXTway robot (a two-wheel balancing robot built from LEGOs).  They have to develop an autonomous control strategy and implement it to race robot around a pre-set track as fast as possible.  Some of my colleagues from Japan developed the balancing algorithm using Simulink and Real-Time Workshop Embedded Coder (available on the File Exchange here).  All the teams have to incorporate that balancing software into their larger design.  I learned that there are many university teams as well as professional engineers from major companies involved in the competition.

Now It’s Your Turn

Are you a mentor?  Are you involved in any of these or other competitions that encourage students to explore STEM fields?  Leave a comment here and share your experience.


Seth Popinchalk is an Application Engineer for The MathWorks. He writes here about Simulink and other MathWorks tools used in Model-Based Design.
  • Guy: @Shahin - The Simulink Control Design toolbox offers functionalities similar to the one provided by the new PID...
  • Shahin Moghimi: Hi, I have the R2008a version, and am wondering if there is such an automatic tool in my version as...
  • ponmani: Respected sir, i am working simulink for the past 6 months. i am trying to place my control algorithm...
  • Seth: @Aleksandar - If you build a Simulink model into an executable using Real-Time Workshop, you will only be able...
  • Aleksandar: Seth, thank you very much! I have additional question. Is it possible to alter Simulink model built into...
  • Seth: I am not sure of your implementation of the D flip flop, and I am not sure how it is causing an algebraic loop...
  • esayas: nice work !
  • Seth: @Checker - Due to the high volume of reservation requests our career fair team had to pre-screen profiles based...
  • Checker: I filled it out couple of days back and got an emial saying that the no. of people they can handle is...
  • Seth: @Jonathan - in the case of the Buffer block, you can not use the result calculated in one part of the model to...

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