Why does my MATLAB function that calls "isempty" on a struct not match the corresponding C++ code generated with MATLAB Coder?

2 次查看(过去 30 天)
I am generating C++ code from a MATLAB algorithm using MATLAB Coder in MATLAB R2024b, and when I reference the numerical outputs of the original algorithm and the generated code against each other, I observe the C++ results do not match the original implementation.
On inspecting the generated code, I see that part of the algorithm is missing in the C++ code. In my MATLAB implementation, there is an if-else statement conditioned on "if isEmpty(x)", where "x" is a struct. However, in the C++ code, only the else branch is generated.
The type of the struct "x" is included in the "args" option for the "codegen" command, and "x" is initialized as "{}" in both the MATLAB and C++ implementations.
Why does the generated code not match the original?

采纳的回答

MathWorks Support Team
When generating code, calls to "isEmpty" that operate on a struct argument will never evaluate to true. As a result, for "if-else" statements that are conditioned on such calls, code is only generated for the "else" branch.
This is illustrated by a simple example: 
function b = structFunExpr (a)
if (isempty(a))
a.x = 0.4;
a.y = 5.0;
else
a.x = a.x + 0.1;
a.y = a.y + 0.1;
end
b = a;
end
If you generate code for "structFunExpr", you will see that code is only produced for the "false" branch. 
To work around this behavior, you can modify the condition to check for some other initialization condition, such as whether the fields of the struct are zero.

更多回答(0 个)

类别

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

产品


版本

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by