Accessing elements in a struct with a string

13 views (last 30 days)
kevin
kevin on 2 Dec 2013
Moved: Steven Lord on 18 Nov 2024 at 14:51
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.

Answers (1)

Stephen23
Stephen23 on 18 Nov 2024 at 9:43
Moved: Steven Lord on 18 Nov 2024 at 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{:})
ans = 3.1416

Categories

Find more on Structures in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!