Accessing elements in a struct with a string
13 次查看(过去 30 天)
显示 更早的评论
I have data that is stored in a struct and I do not always know the names of the fields. Example data.Struct3.Element5.a. If i have Struct3.Element5.a stored as a string, full_name{5,1}=Struct3.Element5.a, why can't i access it by data.(full_name2{5,1})? Returns Reference to non-existent field 'Struct3.Element5.a'. I can store each field in a seperat cell and access it like this data.(full_name(5,1).(full_name(5,2)).(full_name(5,3), but would rather not have to do this as the data may be stored in multiple nested structs.
0 个评论
回答(1 个)
Stephen23
2024-11-18,9:43
移动:Steven Lord
2024-11-18,14:51
"If i have Struct3.Element5.a stored as a string, full_name{5,1}=Struct3.Element5.a, why can't i access it by data.(full_name2{5,1})?"
Because each field contains a completely separate structure array (which just happen to be nested inside other structures, but that does not make all of them into one structure array). And MATLAB indexes into one array at a time, it does not allow indexing into multiple arrays with one index operation (dot indexing is just some kind of of indexing).
It is a very common misconception about nested structures that they are all one structure that can be accessed using one dot-indexing operation:
"I can store each field in a seperat cell and access it like this data.(full_name(5,1).(full_name(5,2)).(full_name(5,3), but would rather not have to do this as the data may be stored in multiple nested structs"
Each field name is an index into a separate structure array, so using a cell array to store them makes a lot more sense. Here is a more versatile approach to using those fieldnames:
data.Struct3.Element5.a = pi;
fld = {'Struct3','Element5','a'};
getfield(data,fld{:})
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!