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 Center および File ExchangeMATLAB Coder についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by