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™.
Default Behavior
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):
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:
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:
- For a and b change the storage class to Define
- 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:
Then in the code, area will show up as a tunable parameter:
And the definition for area contains the mathematical expression:
Because I used the Define storage class for a and b, those show up as macros in the model header file:
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
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.
コメント
コメントを残すには、ここ をクリックして MathWorks アカウントにサインインするか新しい MathWorks アカウントを作成します。