Accessing elements in a struct with a string
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposte (1)
Stephen23
il 18 Nov 2024
Spostato: Steven Lord
il 18 Nov 2024
"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 Commenti
Vedere anche
Categorie
Scopri di più su Structures in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!