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

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

채택된 답변

MathWorks Support Team
MathWorks Support Team 2022년 11월 23일
편집: MathWorks Support Team 2022년 10월 8일
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.

추가 답변 (0개)

카테고리

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

태그

아직 태그를 입력하지 않았습니다.

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by