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

2 次查看(过去 30 天)
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.

回答(1 个)

Mukund Sankaran
Mukund Sankaran 2023-6-15
编辑:Mukund Sankaran 2023-6-16
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!

类别

Help CenterFile Exchange 中查找有关 MATLAB Coder 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by