Guy on Simulink

Simulink & Model-Based Design

Specifying Variable Values Using Mathematical Expressions: Generated Code

Some time ago, I published a post where I described how to specify variable values using mathematical expressions using the slexpr function. This triggered a lot of questions about the impact on the code generated from a model using Embedded Coder™.
To help answering those questions, I am happy to welcome back guest blogger David Balbuena.

Default Behavior

My first thought when I read Guy's recent post on slexpr was "What about code generation?!"
Today I will show how you can use Embedded Coder™ to preserve parameter expressions in the generated code.
Let's take the part of Guy's model that uses the variable area (I'll explain why I am leaving out the hypotenuse later):
area_model.png
Where area is created using this code:
a = Simulink.Parameter(3);
b = Simulink.Parameter(4);
area = Simulink.Parameter(slexpr("(a*b)*0.5"));
If you generate code using the default settings of Simulink.Parameter objects, the evaluated value of area gets inlined:
nontunable_code.png

Specifying Storage Classes to Preserve Expressions

It is possible for Embedded Coder to preserve the mathematical expression in the generated code by making two changes:
  1. For a and b change the storage class to Define
  2. For area, set the storage class to ExportedGlobal
I like to use the Code Mappings Editor (ctrl+shift+C) for that, since I can mass-edit code generation settings with ctrl+click:
tempgif.gif
Then in the code, area will show up as a tunable parameter:
tunable_code.png
And the definition for area contains the mathematical expression:
area_definition.png
Because I used the Define storage class for a and b, those show up as macros in the model header file:
expression_params_definition.png
These are not the only storage classes you can use. The general rule is:
  • For parameters used in the expression (a and b), the storage class has to generate a macro, such as Define and ImportedDefine
  • For the derived parameter (area), storage class must be non-Auto (for example ExportedGlobal or ExportToFile)
In my example, I left out the hypotenuse (sqrt(a^2+b^2)) parameter because only certain mathematical expressions are supported, and the calculation for the hypotenuse has two unsupported parts: the sqrt() function and the ^ operator
You can read more of the details and limitations in the documentation.

Now it's your turn

We are aware that this feature comes with many limitations and supports only a limited set of operations. We are considering adding support for more operations and removing some of those limitations. If you are interested by this feature but are impacted by a limitation, let us know in the comments below to help us prioritize.
|
  • print

评论

要发表评论,请点击 此处 登录到您的 MathWorks 帐户或创建一个新帐户。