Why do I get the error "Attempt to extract field 'x' from 'double'." when I use MATLAB Coder in MATLAB R2022b?
5 次查看(过去 30 天)
显示 更早的评论
MathWorks Support Team
2023-7-28
编辑: MathWorks Support Team
2024-6-20
I have the following simplified function:
function out = fnName()
s = [ ];
s.x = 10; % This is the line where I get the error.
end
It runs fine in MATLAB but when I use MATLAB Coder to generate code for it, I get the following error:
Attempt to extract field 'x' from 'double'.
Why do I get this error and how do I resolve it?
采纳的回答
MathWorks Support Team
2024-5-24
编辑:MathWorks Support Team
2024-6-20
In the context of code generation, a variable's datatype cannot be changed once it is assigned to a value. In the function you provided,
s = [];
creates an empty variable with the default data type of “double” in MATLAB. You can check its data type by running:
class(s)
in MATLAB Command Window.
From the perspective of MATLAB Coder, you tried to change the type of "s" from "double" to "struct". While in MATLAB, you can assign a variable with a value of different data type, it generally causes issues during code generation.
A workaround for this issue is to remove the first assignment to "s", so that it is never a "double" to begin with. The function becomes
function out = fnName()
s.x = 10;
end
Now, MATLAB Coder knows that "s" is intended to be a struct with field "x".
0 个评论
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!