Coder: change once for all in the generated C++ code data set as Constant for the coder

3 views (last 30 days)
Hi!
I'm using Matlab coder to convert code which calls functions from (non linear) MPC Toolbox into C++ code.
I created an "nlmpcobject" and filled its fields like this:
real_space_dim = 6;
nx = real_space_dim;
ny = real_space_dim;
nu = real_space_dim + 1;
nlmpcobj = nlmpc(nx,ny,nu);
timeStep = 0.01;
p = 10;
c = 10;
nlmpcobj.Ts = timeStep;
nlmpcobj.PredictionHorizon = p;
nlmpcobj.ControlHorizon = c;
nlmpcobj.Model.NumberOfParameters = 13;
and then converted these data into two structures, "coreData" and "onlineData" with the Matlab dedicated function:
[coreData,onlineData] = getCodeGenerationData(nlmpcobj,x0,mv0,params);
Now, when I use "codegen" to generate C++ code I have to set "coreData" as constant, otherwise I get some errors from the coder.
coder.Constant(coreData);
Doing so, its fields are no longer accessible in C++ code and are displayed directly with their numeric values (ex. "10" instead of "p").
Is there a way to keep these fields with their names and set them as global variables so that I can change them once for all in the generated C++ code even if "coreData" has been declared constant?
Until now, every time I want to change for example my prediction horizon (i.e. very frequently) I have to regenerate the code, but it's very time-wasting....
Thank you in advance for your help!

Answers (1)

Sachin Lodhi
Sachin Lodhi on 30 Aug 2023
Based on my understanding of your issue, you would like to generate code that retains the variables without being substituted by their values. MATLAB Coder offers the ability to specify entry point functions, and it preserves the interface of these functions without modification. However, for other functions called within the entry point function, MATLAB Coder optimizes them for improved execution speed, resulting in direct substitution of variable values where they are accessed. To ensure that variables are not substituted, you can specify the function names as entry point functions during code generation. By doing so, you will be able to access the variables by their names.
I recommend referring to the answer provided in the following question, as it contains additional helpful information related to your query.
I hope the above answer helps you in accessing the variables.

Community Treasure Hunt

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

Start Hunting!