How to access data in structures?

77 次查看(过去 30 天)
I'm currently learning how to use structures in MATLAB and I'm finding it a little more confusing than cells and other regular arrays. I'm confused on how to call data stored in specific fields of a structure. I understand the format is "nameofstructure"."nameoffield", but I'm struggling with how to get the data I need from the structure without knowing the name of the fields. Say I had a structure with 2 fields, how would I go about getting the infomation from either one without knowing the name of the field? I tried pulling the names of the fields in a function and using them like so
fieldnames = fieldnames(structure)
fieldInedd = fieldnames(2)
informationfromthisfield = structure.fieldIneed
But this doesn't give a field that matlab can recognize and draw data from. Could anyone help?

采纳的回答

Walter Roberson
Walter Roberson 2020-10-17
fieldnames = fieldnames(structure)
fieldInedd = fieldnames{2}
informationfromthisfield = structure.(fieldIneed)
Notice the () around the field name: it is important. This syntax is "dynamic field names".
This syntax of dot followed by a variable name or expression in () is also used for referencing table variables that are not valid MATLAB variable names.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

标签

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by