Why do I get an error when choosing a field of a struct with the '.()' notation in a MATLAB Function block?

1 view (last 30 days)
It is sought to choose dynamically the field of a struct inside a MATLAB Function block in Simulink using the '.()' notation, namely,
y = mystruct.(myfield);
However, this construct leads to the following error message:
Non-constant expression or empty matrix. This expression must be constant because its value determines the size or class of some expression.
Function 'MATLAB Function' (#24.286.291), line 17, column 16:
"field"
Launch diagnostic report.
Why do I get the above error when choosing a field of a struct with the '.()' notation in a MATLAB Function block?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 23 Nov 2022
Edited: MathWorks Support Team on 8 Oct 2022
The construct "mystruct.(myfield)" in a MATLAB Function block is not supported.
The reason is that an input to the MATLAB Function block in this case dictates which field of the bus/struct is to be assigned to the output. The reason it works when the index is hard-coded is that the expression can simply be evaluated before code generation and it does not depend on an input.
Another way to explain this limitation is to understand how code generation resolves symbols in dot notation for indexing elements of a structure: 
Consider the following example in the table:
inbus.ele3.a1 --- Value of field a1 of field ele3, a substructure of structure input inbus 
Basically, if it is being indexed twice in the same expression using dot notation, the hierarchy goes "structure->substructure->field".
Now consider your line of code above, namely,
mystruct.(myfield)
Here, "myfield" is not a substructure of "mystruct". Instead, "myfield" is supposed to evaluate to a character array that corresponds to one of the fields of "mystruct". This will not work because it violates the indexing syntax explained on the documentation page above.
Please avoid this construct for choosing the fields of a struct/bus and please consider using a more deterministic logic for this purpose.

More Answers (0)

Tags

No tags entered yet.

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!