Azzera filtri
Azzera filtri

How to prevent replacing variables with their values in matlab coder?

3 visualizzazioni (ultimi 30 giorni)
Let's say I have the following function in Matlab:
function y = dum_func(x)
my_constant = 5;
y=my_constant+x;
end
The corresponding C++ function generated by the coder is the following:
double dum_func(double x)
{
// 'dum_func:3' my_constant = 5;
// 'dum_func:4' y=my_constant+x;
return x + 5.0;
}
Question) Is there a way to keep my_constant as variable in the c++ code?
Thanks.

Risposte (1)

Mukund Sankaran
Mukund Sankaran il 15 Giu 2023
Modificato: Mukund Sankaran il 16 Giu 2023
Hello,
What you are observing is due to an optimization called constant folding. This is explained here: https://www.mathworks.com/help/coder/ug/matlab-coder-optimizations-in-generated-cc-code.html
For the particular example you shared, unfortunately, there is no straightforward way to get the generated code looking the way you expect today. However, FWIW, if your MATLAB code is rewritten to look like this:
function y = dum_func(x)
my_constant = 5;
coder.ceval('(void)', coder.ref(my_constant));
y = my_constant + x;
end
Then the generated code will look like this:
double dum_func(double x)
{
double my_constant;
my_constant = 5.0;
(void)(&my_constant);
return my_constant + x;
}
The use of ceval might stop all optimizations on the variable my_constant and yield the result above.
Hope this helps!

Categorie

Scopri di più su MATLAB Coder in Help Center e File Exchange

Prodotti


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by