Why do I get the error "Attempt to extract field 'x' from 'double'." when I use MATLAB Coder in MATLAB R2022b?
5 views (last 30 days)
Show older comments
MathWorks Support Team
on 28 Jul 2023
Edited: MathWorks Support Team
on 20 Jun 2024
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?
Accepted Answer
MathWorks Support Team
on 24 May 2024
Edited: MathWorks Support Team
on 20 Jun 2024
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 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!