Why does my MATLAB function that calls "isempty" on a struct not match the corresponding C++ code generated with MATLAB Coder?
2 次查看(过去 30 天)
显示 更早的评论
MathWorks Support Team
2025-9-29
回答: MathWorks Support Team
2025-10-28
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
2025-9-29
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 个评论
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!