Why do I get the error "Attempt to extract field 'x' from 'double'." when I use MATLAB Coder in MATLAB R2022b?

조회 수: 5 (최근 30일)
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
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개)

카테고리

Help CenterFile Exchange에서 MATLAB Coder에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by