How do I generate code from Simulink to generate composite C definitions?

I have a Simulink model in MATLAB R2022a, which contains three constant variables called "A", "B" and "C". However, instead of setting constant "C" to a numerical value, I would like to set the value of "C" to be equal to "A + B" such that I get the following definitions when I generate C code from the model: 
#define A 5
#define B 6
#define C (A + B)
Is this possible to achieve in Simulink?

 Accepted Answer

Achieving this workflow in Simulink depends on if "C" is a dependent variable or a tunable parameter -
1) If "C" is a dependent variable, then "C" depends on the value of constants "A" and "B". Thus in this circumstance, "C" must have a storage class of "Define" and constants "A" and "B" must have the storage class of "ImportedDefine".
2) If "C" is a tunable parameter, then "C" must have the storage class of "ExportedGlobal" and constants "A" and "B" must have the storage class of "Define" or "ImportedDefine".
For more information about storage classes when a Simulink parameter is an expression, please refer to the following documentation:
Below are the steps to follow to achieve this outcome if "C" is a dependent variable. These steps can be adapted for the case where "C" is a tunable parameter by setting the parameters "A", "B" and "C" to the correct storage class as mentioned before.
1) Create "A", "B" and "C" as Simulink Parameters and assign values to each parameter by running the command below in the MATLAB Command Window:
A = Simulink.Parameter;
A.Value = 5;
B = Simulink.Parameter;
B.Value = 6;
C = Simulink.Parameter;
C.Value = slexpr("A + B");
2) In Simulink, open the model explorer. This can be achieved by pressing "Modelling" in the top bar and then "Model Explorer".
3) Change the storage class of "A" and "B" from "Auto" to "ImportedDefine" and the storage class of "C" to "Define" from the "Code Generation" tab on the right.
4) Set the "HeaderFile" attribute to the name of the header file that declared them
5) Define values for "A" and "B" in your header file
6) Run and generate code for simulation, your "<NameOfHeader>.h" file will include the definitions for "A" and "B" and Simulink will add a definition for "C" to be "A + B" as desired.

More Answers (0)

Categories

Find more on Simulink Coder in Help Center and File Exchange

Products

Release

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!