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

5 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

MathWorks Support Team
MathWorks Support Team il 24 Mag 2024
Modificato: MathWorks Support Team il 20 Giu 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".

Più risposte (0)

Categorie

Scopri di più su MATLAB Coder in Help Center e File Exchange

Prodotti


Release

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by