Seth on Simulink
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.

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.

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.
01:48 UTC |
Posted in Code Generation, Signals, What's new? |
Permalink |
3 Comments »
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 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.
03:00 UTC |
Posted in Community, Fun |
Permalink |
3 Comments »
October 16th, 2009
Radar Tracking in Simulink: Variable Size Signals
This week I welcome guest blogger Aarti Ramani to talk about a long requested feature, variable size signals in Simulink.
Depending on target ranges, radar systems operate in
different modes (different lengths of data etc). Let’s assume we have two
planes at two different altitudes. Now, what happens if there is a new plane in
sight? Since the number of targets being detected by the radar is now changing,
how would you use Simulink to add this plane to its tracking list?

A short and simple answer to this question is: Variable
Size Signals.
I’ve read many customer requests wanting to be able to
change the dimensions of their Simulink variables while the simulation runs. Be
it a radar system which needs to operate in different modes based on its target
range to a simple combustion engine that needs to change its frame size based
on the number of samples per cycle, each of these system dynamics work with
signals whose sizes change during model execution.
Although, earlier I had to tell our customers that Simulink
did not have this capacity and you could not change a model’s signals
dimensions during execution; with R2009b, Simulink now supports variable-size
inputs and outputs in over 40 Simulink blocks.
How does one create a variable size signal?
There are several methods of creating a variable size
signal: Switch blocks; Multi-Switch blocks with different input sizes; a Selector
block indexing options or custom code blocks (S-functions and Embedded MATLAB
blocks).
A common way of generating variable-size signals is to use a
Switch block for which each of the input signals differ in size. The Switch
Block now allows variable size signals to be passed in as inputs:

By simply selecting the option “Allow different data input
sizes”, you can obtain a variable size output signal whose dimensions change
with time.
As an
experiment, let us look at a simple demo model “sldemo_varsize_basic.mdl”. This demonstration
contains examples of how to use variable-size signals in a Simulink model, and
to show what kind of operations you can apply to them.

Look at
how the Switch block, allowing 2 inputs of different dimensions, can be used
for operations like addition, vector concatenation etc.
You can also use the
“Selector” blocks to create a variable size signal. The Selector block generates as
output selected or reordered elements of an input vector, matrix, or
multidimensional signal. Using the “Starting and ending indices (port)”
indexing option, you can allow inputs of variable dimensions to generate
variable size signals.

You can use the Selector block to subreferece a matrix as shown below:

How can I get the current dimensions or width of a
variable-size signal?
You can use the Probe block to output the width of a signal.

The Probe
allows you to visualize and save the signal dimensions and view the I/O and
state data for blocks selected. This could also be used in a calculation that
requires sample size information.
How can I convert a variable-size signal into a
fixed-size signal?
To convert a variable size signal into a fixed size signal,
you can use the “Assignment” block. The variable-size signal feeds into the second
input port of the Assignment block and can be used to convert the incoming
signal into a fixed size signal.
By allowing signal sizes in Simulink models to vary during
execution, one can easily model systems with varying environments, resources,
and constraints. So, coming back to our radar system, using variable size
signals, you can now create a conceptual air traffic control (ATC) radar
simulation based on your radar range equation(s):

For more details on how this snazzy feature works, check out
the Variable
Sizing documentation.
Now it’s your turn
Do you plan to upgrade to R2009b and use variable size signals?
Leave a comment here and tell me what you plan to model.
19:00 UTC |
Posted in Guest Blogger, Signal Processing, Signals, What's new? |
Permalink |
3 Comments »
October 6th, 2009
MathWorks Hosts EcoCAR
Recently, when I arrived at work, I found this parked on the
lawn:

This is the EcoCAR from the EcoCAR Challenge. MathWorks hosted
about one hundred students from the EcoCAR teams for the EcoCAR Year 2 Fall
Workshop.
A Big Shiny Embedded Target
When I first saw the EcoCAR sitting on the lawn, I wondered
what system target file they might use:

I’m sure there are a lot of cool things these students will
be able to do with a great piece of hardware like this, but in many ways, it’s
just a big, shinny embedded target.
What is EcoCAR?
EcoCAR is an academic competition. A quote from ecocarchallenge.org
sums it up:
“The competition challenges 17 universities across North
America to reduce the environmental impact of vehicles by minimizing the
vehicle’s fuel consumption and reducing its emissions while retaining the
vehicle’s performance, safety and consumer appeal. Students use a real-world
engineering process to design and integrate their advanced technology solutions
into a 2009 Saturn Vue.”
The students had 5 days of training in different tracks to
learn and apply MathWorks tools to the design problems facing them. If you
read the Green Car Garage blog, you
may have read about the
event and the
fun teams had during their visit to Boston. Nicole Lambiase from Argon National Lab wrote a post
commenting that it really takes a village to make these competition events
run smoothly. Some of the people in that village are members of the
Model-Based Design community. A lot of my colleagues volunteer with EcoCAR
Challenge. Many of them traveled from our Michigan office to lead trainings
and mentor students that attended.
The Trouble with Model-Based Design
The trouble with Model-Based Design is that there are very
few people and institutions available to help you learn it. I never had a
class on Model-Based Design when I went to school. The EcoCAR Challenge is an opportunity
to develop the next generation of engineers skilled in Model-Based Design. MathWorks
is very committed to mentoring these future engineers. This aligns with our academic
mission to accelerate the pace of learning, discovery, and research in
engineering and science.
How about you?
How did you learn about modeling and Model-Based Design? Who
was your mentor? Leave a comment here and
share your story.
03:00 UTC |
Posted in Community, Fun, Model-Based Design |
Permalink |
1 Comment »
September 25th, 2009
Custom Components in Physical Models
This week I want to introduce
guest blogger Steve
Miller to talk about the Simscape language.

Introduction to the Simscape
Language
I’ve been working with MATLAB and
Simulink since my college days, and one of the things I liked most about these
tools is that I’m free to create just about anything with the commands and
blocks. Whenever my boss asked me, “Do you think you could use MATLAB to...,”
the enthusiastic “Yes!” was halfway out of my mouth before he even reached the
end of the sentence.
When I started working with the physical
modeling products at The MathWorks,
I was hoping that I’d have the same freedom there. Well, starting with Release
2008b, I do! Using the Simscape language (an
enhancement to Simscape, which was first released in R2007a), I can create my
own physical modeling blocks just like I created cool MATLAB scripts and
Simulink subsystems to solve all those tricky problems my boss threw at me.
What is the Simscape language?
The Simscape language is a
MATLAB-based, object-oriented language for modeling physical systems. The big
difference here is that I can use this textual language to create components
that have physical connections, such as hydraulic ports on valves and electrical
terminals on resistors, instead of inputs and outputs like I’m used to doing in
Simulink. Why is this important? Well the models built with physical
connections are much easier to understand – models of electrical systems look
like an electrical schematic. And, if I create something useful and I want to
reuse it in another model, it is much easier, for I don’t have to worry about
routing inputs and outputs -- I just plug my new electrical component into the
circuit and try it.
Here is an example of a component
I have defined using the Simscape language. It’s a DC motor. You’ll see that
it has four physical ports (not inputs and outputs) – two electrical and two
mechanical. These physical ports let me plug the component into a physical
network.

How does it work?
You can use the Simscape language
to define physical domains, components, and libraries of components. It’s
usually easiest to look at an example, so let’s look at the definition of a DC
motor created in the Simscape language.
Here we see the first 11 lines of
the file. This is where we define the component name, add a description, and
define the physical ports:

You can see that we have two
electrical (+ and – terminals) and two mechanical rotational ports (motor shaft
and motor housing). These are reflected in the component shown above.
In the next 6 lines of the file,
we define the parameters (including units!). These are the values that I or
another user may want to change:

You’ll notice that in the final
component, the prompt, the default value, and the units all show up in the
dialog box shown here:

Just like most Simscape blocks,
there a link to the source code! In lines 18-23 of the file, we define the
variables associated with the physical domains (electrical and mechanical) we need for the equations we will define in the
equations section.

In the setup section, we set up
the connections between the variables to the physical ports. Remember
Kirchoff’s laws? Well, we’re essentially applying them to both the electrical
and mechanical domains (yep, they work in other physical domains, too, if you
define them properly).

You’ll also notice that we have used
MATLAB to make sure that the value of the resistance in the dialog box is not
less than zero. I can use MATLAB code in this section to do other things like
calculate values or initialize variables. All that MATLAB I learned is not
going to waste!
In the last lines of the file, I
define the equations for the motor. Take a look:

See
the “==” symbol there? I’ve used that to define an implicit equation. This
means I have set up a relationship between these quantities (including time
derivatives – see the .der?).
I’m not assigning values, nor does this represent a Boolean
expression. I could have defined them as shown below and the results would be
the same:

And there you have it! Once I
have defined the file, I execute ssc_build
and it produces a Simscape component I can connect to other Simscape components
in my physical model.
Videos of Simscape language in
action
I have made a video demo of
modeling a nonlinear spring using the Simscape language. Take a look to see the blocks in use and the build
process.
For a more complete experience,
watch this
webinar on the Simscape language.
Now it’s your turn
Want a closer look at this
example?
Download it from the
MATLAB Central File Exchange.
Are you using the physical
modeling tools? Have you tried the Simscape language? Post a
comment here and tell us
about it.
16:00 UTC |
Posted in Guest Blogger, Physical Modeling, What's new? |
Permalink |
No Comments »
September 18th, 2009
How do I test for NaN in Simulink R2009b? (NEW!)
Back in February 2009 I posted about how
to test for NaN in Simulink. The approach I talked about was more of a
logical experiment based on the special properties of NaN than an ideal
software solution. In Simulink R2009b the Relational
Operator block got an upgrade to include isNaN. Let’s see how it works.
Relational Operator Block Upgrade
The Relational Operator is often used to compare signals and
test for greater than (>), equals (==), and more. In R2009b it has the
following new single input modes: isNaN, isFinite, and isInf.


These functions are familiar to those who program in MATLAB
and they work the same way. When the input signal has the properties we are
testing for, the block outputs true.
How does it work?
I talked to my colleague Omar who upgraded the block and he
shared with me some key points. He mentioned that the block handles:
- real and complex signals
- any data type supported by Simulink including fixed point types
- endianness of your platform
These new operators are only meaningful with data types that
can represent Inf and NaN. So how does it work with non-floating point
types? If you pass in an integer, or a fixed-point type that cannot
represent NaN of Inf, the block returns false. This is a key point for
workflows where you might find yourself switching the data types in your design.
This often happens when selecting proper fixed-point data type properties. If
you are running simulations to gather ideal double precision results, you may
need to handle Inf and NaN. When converting the model to fixed-point for implementation,
the algorithm does not require any modifications.
Generated Code
The code generated for the isNaN function looks like this:
34 /* Outport: ‘<Root>/Out1’
incorporates:
35 * Inport: ‘<Root>/In1’
36 * RelationalOperator: ‘<Root>/Relational Operator’
37 */
38 isNaNCode_Y.Out1 = rtIsNaN(isNaNCode_U.In1);
The function rtIsNaN is part of rt_nonfinite.c:
61 /* Test if value is not a number */ 62 boolean_T rtIsNaN(real_T value) 63 { 64 65 #if defined(_MSC_VER) && (_MSC_VER <= 1200) 66 67 /* For MSVC 6.0, use a compiler specific comparison function */ 68 return _isnan(value)? 1U:0U; 69 70 #else 71 72 return((value!=value) ? 1U : 0U); 73 74 #endif 75 76 }
Further Optimization using Target Function Library
If your embedded target environment has a special function
for handling tests for NaN, Inf or Finiteness you can use the Target
Function Library to replace the call to rtIsNaN with that call.
What do you think?
Will you use the isInf, isNaN and isFinite mode of this
block? Leave a comment
here to tell me how.
16:00 UTC |
Posted in Numerics, What's new? |
Permalink |
1 Comment »
September 9th, 2009
New Stuff – Simulink R2009b
Last week the MathWorks released the R2009b family of
products. There are many new capabilities in the latest release and with this
blog post, I want to highlight a some of the features in Simulink I’m really
excited about. While you read this, start installing the latest products from
the MathWorks.com
downloads area (login and license required).
Reading the release notes is so R2007b!
Did you know that there is a presentation containing highlights
and screen shots from R2009b Simulink? If you have missed this in the
past, you can go back and check out R2008a,
R2008b
and R2009a
highlights. Try it yourself, and browse through all the cool
new features in R2009b Simulink.

Model Reference Protected Models!
Share your model functionality without sharing your model
intellectual property! Anyone with R2009b Simulink can use a protected model.
If you have a license to Real-Time Workshop, you can create a protected model.

Model Reference Variants
If you have multiple implementations of your component model,
variant objects enable you to control the implementation used. This allows you
to globally control and coordinate switching between variant implementations of
your model.

Tabs in the Mask Editor!
Now you can create tabs in your custom block masks.

Variably Sized Signals!
Special blocks and Embedded MATLAB now support dynamically
sizing signals during simulation!

The SIM command can return a single output!
The SIM command has a new single output syntax so all your results
are part of a single SimulationOutput object. This enables SIM to be called
within a PARFOR loop, thus enabling easy parallel Simulation using the Parallel
Computing Toolbox.
paramNameValStruct.SimulationMode = 'rapid';
paramNameValStruct.AbsTol = '1e-5';
paramNameValStruct.SaveState = 'on';
paramNameValStruct.StateSaveName = 'xoutNew';
paramNameValStruct.SaveOutput = 'on';
paramNameValStruct.OutputSaveName = 'youtNew';
simOut = sim('vdp',paramNameValStruct);
New Library Links Tool for fixing broken links!
After making changes to a model and disabling library links,
the Library Links tool will enable you to reestablish those links to your
library. Each change in the model can be pushed back into the library, or the
block can be restored from the original library source.

Now it’s your turn
Have you downloaded R2009b? Leave a comment here and
tell me about your favorite new features.
01:56 UTC |
Posted in Libraries, Masking, Model Reference, Simulation, What's new? |
Permalink |
5 Comments »
August 28th, 2009
BEEP, Simulink versus MATLAB
Did you ever notice that a BEEP in Simulink means something
different from a BEEP in MATLAB?
BEEP, What BEEP?
What I’m talking about is that bell character you sometimes
hear. In older version of MATLAB (Pre R14), you could actually display a beep
on the screen.
>> fprintf('\a')
>> disp(char(7))
In more recent version, the command window doesn’t display
the BEEP character. Instead, you can call the function BEEP.
>> beep
You hear it under different circumstances for Simulink
versus MATLAB.
MATLAB BEEP == Error
In MATLAB, the BEEP alerts you to an error. Sometimes you
get it because your calling syntax is wrong, sometimes when the tab completion can’t
find anything. In MATLAB, BEEP is bad.
>> plot(x,y
??? plot(x,y
|
Error: Expression or statement is incorrect--possibly unbalanced
(, {, or [.
Simulink BEEP == Done
In Simulink, the BEEP happens when your simulation is
finished. It is a beautiful sound. The BEEP is an alert to tell you the work
is done. The fruit of your simulation is ready to harvest. It is time to
review your results. In Simulink, BEEP is a good sound.
>> vdp
>> set_param(bdroot,'SimulationCommand','start')

Leave your comments, after the BEEP. (THANK YOU Jeannette for alerting me to the difference.)
21:44 UTC |
Posted in Fun |
Permalink |
2 Comments »
August 20th, 2009
A Better If-Else Construct
In a previous post, I answered a question about how
to model an If-Else behavior. Here I will restate the algorithm I want to create:
if(sel==0)
out = 2*in1;
elseif (sel==1)
out = 3*in2;
The first answer I gave relied upon a Switch block and the Conditional
Input Branch Execution optimization to get an efficient If-Else construct
in the model. While this works, I don’t like reliance on an optimization to
provide good behavior. Sometimes, small changes to the model prevent Simulink
from applying an optimization. I think it is best to implement requirements explicitly.
In this post, I want to show you a way to model explicitly an If-Else conditional
execution behavior.
Conditionally Executed Subsystems and Merge
The If-Else construct requires decision logic to control the
execution of algorithm contained within the expression. One way to do this is
using the If block (from the Ports & Subsystems library), combined with the
If Action Subsystem. The If Action Subsystem executes based on the conditional
expression in the If block. If you have used Function Call subsystems, this is
very similar.

The If block provides control over If and ElseIf conditions,
and there is even an option to provide an Else signal.

This model will give you the conditional execution of the
two subsystem, however, the subsystems write their outputs to separate signals.
How do you get two subsystem to write to the same signal?
Merge the Signals
The Merge block provides a way for both subsystems to write
to the same signal.

In many ways, the Merge block doesn’t behave like a block
with the traditional input/output relationship. I think of it more like a
jumper across multiple wires. The merge block specifies that all signals
connected to it have the same value and actually share the same memory. This
is the programming practice of specifying multiple writers to the same
variable.
Generated Code with Merge
The code generated from the above model looks a lot like our
original algorithm.
34 /* If: '<Root>/If' incorporates: 35 * ActionPort: '<S1>/Action Port' 36 * ActionPort: '<S2>/Action Port' 37 * Inport: '<Root>/In3' 38 * SubSystem: '<Root>/If Action Subsystem' 39 * SubSystem: '<Root>/If Action Subsystem1' 40 */ 41 if (sel == 0.0) { 42 /* Gain: '<S1>/Gain' incorporates: 43 * Inport: '<Root>/In1' 44 */ 45 out = 2.0 * u1; 46 } else { 47 if (sel == 1.0) { 48 /* Gain: '<S2>/Gain' incorporates: 49 * Inport: '<Root>/In2' 50 */ 51 out = 3.0 * u2; 52 } 53 }
Correct use of Merge
Because Merge blocks are a memory specification rather than
an algorithmic construct, there are some guidelines
for using merge blocks. The documentation shows some correct and incorrect
usage patterns. If you use merge block in your model, I suggest you run the Model
Advisor Check for proper Merge block usage.
Now it’s your turn
Do you use the Merge block in your models? Leave a comment here and
share your experience.
01:55 UTC |
Posted in Code Generation, Modeling, Real-Time Workshop, Simulink Tips |
Permalink |
4 Comments »
August 11th, 2009
How Many Blocks are in that Model?
My colleague Sam and I wanted to find an example model with
about 10,000 blocks. I suggested the HL-20 model from the Aerospace Blockset, asbhl20.mdl.
Sam decided to measure the total number of blocks by running sldiagnostics:
>> [t,s] = sldiagnostics('asbhl20','CountBlocks');
s(1)
ans =
isMask: 0
type: 'asbhl20 Total
blocks'
count: 5700
Sam quickly sent me a message saying that the HL-20 model only
had 5700 blocks. What gives?
What is SLDIAGNOSTICS?
First, let us discuss a little history of sldiagnostics.
Over the years, Simulink developers have worked with many customers to learn
about their modeling styles and assist in debugging problems. Unfortunately some
customers are unable to share their models because they might contain
proprietary information. The solution these developers created were a series
of scripts that would quickly gather information about a model without any model
algorithm information. These collected scripts then became the sldiagnostics
function. Because the output of these scripts was generally devoid of any
proprietary data, even customers who could not share their models were able to provide
the diagnostic information instead.
Most of the checks done by sldiagnostics help you gather an
understanding of the model as a whole. This is a great help in learning about
models rather than having to browse through every system one-by-one.
CountBlocks
The diagnostic information Sam gathered was the output of
CountBlocks. Here is a part of the text report for the HL-20 model.
Finished counting blocks in 'asbhl20'.
Found 5700 blocks.
asbhl20 Total blocks : 5700
Abs : 16
ActionPort : 11
Assertion : 2
Bias : 6
BusCreator : 46
BusSelector : 126
<snip>
Inport : 1175
InportShadow : 49
Integrator : 43
Interpolation_n-D : 1
Logic : 6
Lookup : 6
Lookup_n-D : 6
Math : 59
Memory : 4
Merge : 4
MinMax : 4
ModelReference
: 9
MultiPortSwitch : 1
Mux : 141
Outport : 669
<snip>
HL-20 Includes Model Reference
The HL-20 model includes 9 ModelReference blocks. (I introduced
some of the basics of model
reference a previous post.) You can see the hierarchy of the model in the
Dependency Viewer instance view.

When I think about a model, I imagine the net collected functionality
represented by it. I think the number of blocks used to create that model is a
simple measure for how much functionality/algorithm there is. Model reference
blocks contain the functionality of the entire model that they reference,
however, sldiagnostics
counts ever Model Reference block as only one block.
The measure I am really looking for is the subsystem
equivalent implementation of all the blocks in the model. To get this for the
HL-20 model, you actually need to count the blocks inside each model referenced
and multiply by the number of instances. I wrote a MATLAB function to do this:
function totalBlocks =
mdlrefCountBlocks(mdl)
% mdlrefCountBlocks Count the
subsystem equivalent number of blocks
% in a model reference hierarchy.
% Copyright 2009 The MathWorks,
Inc
%% Open the model
open_system(mdl)
%% Get instance information
[mDep,mInst] = find_mdlrefs(mdl);
% Open dependent models
for i = 1:length(mDep)
load_system(mDep{i})
end
%% Count the number of instances
of each dependency
mCount = zeros(size(mDep));
mCount(end) = 1; % Last
element is the top model, only one instance
for i = 1:length(mInst)
mod = get_param(mInst{i},'ModelName');
mCount = mCount + strcmp(mod,mDep);
end
%%
for i = 1:length(mDep)
disp([num2str(mCount(i)) ' instances of
'
mDep{i}])
end
disp(' ')
%% Loop over dependencies, get
number of blocks
s = cell(size(mDep));
for i = 1:length(mDep)
[t,s{i}] = sldiagnostics(mDep{i},'CountBlocks');
disp([mDep{i} ' has ' num2str(s{i}(1).count)
'
blocks'])
end
%% Multiply number of blocks,
times model count, add to total
totalBlocks = 0;
for i = 1:length(mDep)
totalBlocks = totalBlocks +
s{i}(1).count * mCount(i);
end
disp(' ')
disp(['Total blocks: '
num2str(totalBlocks)])
Total Blocks
Here are the results of running this function:
>> total = mdlrefCountBlocks('asbhl20');
3 instances of asbhl20_FCSApp
3 instances of asbhl20_FDIRApp
3 instances of asbhl20_GuidanceApp
1 instances of asbhl20
asbhl20_FCSApp has 115 blocks
asbhl20_FDIRApp has 1248 blocks
asbhl20_GuidanceApp has 388 blocks
asbhl20 has 5700 blocks
Total blocks: 10953
Now it’s your turn
In the end, we can see the HL-20 model has almost 11K
blocks. Do you use model reference? How many total blocks are in the hierarchy
of your largest model? Use the script above to gather this data and post it in
the comments here.
15:46 UTC |
Posted in Commands, Debugging, History, Model Reference |
Permalink |
7 Comments »
|
Recent Comments