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

3 vues (au cours des 30 derniers jours)
Kara657
Kara657 le 15 Juin 2023
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.

Réponses (1)

Mukund Sankaran
Mukund Sankaran le 15 Juin 2023
Modifié(e) : Mukund Sankaran le 16 Juin 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!

Catégories

En savoir plus sur MATLAB Coder dans Help Center et File Exchange

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by