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

4 visualizaciones (últimos 30 días)
Kara657
Kara657 el 15 de Jun. de 2023
Editada: Mukund Sankaran el 16 de Jun. de 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.

Respuestas (1)

Mukund Sankaran
Mukund Sankaran el 15 de Jun. de 2023
Editada: Mukund Sankaran el 16 de Jun. de 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!

Categorías

Más información sobre MATLAB Coder en Help Center y File Exchange.

Productos


Versión

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by