This week I asked Michael Carone to introduce a relatively
new Stateflow capability, Simulink Functions.
Did you ever want to put a Simulink block inside of a
Stateflow chart? Well, if you have R2009a
or R2009b,
you can!
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.
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!
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
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.
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)
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.
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.
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.
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.
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.
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 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.
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.
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.
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.
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.
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).
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)
In another grouping, the inputs to the operators have very
different magnitudes.
(1e-16 + 1e30) + (1e-16 - 1e30)
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.
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.
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.
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.
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.
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!
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.
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.
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.
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.
It is not every day that I attend a speech by political
leaders of the Commonwealth of Massachusetts.
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. 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 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.
Recent Comments