Why does my MATLAB function that calls "isempty" on a struct not match the corresponding C++ code generated with MATLAB Coder?
1 view (last 30 days)
Show older comments
MathWorks Support Team
on 29 Sep 2025
Answered: MathWorks Support Team
on 28 Oct 2025
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?
Accepted Answer
MathWorks Support Team
on 29 Sep 2025
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 Comments
More Answers (0)
See Also
Categories
Find more on Simulink Coder in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!