How to access data in structures?

77 vues (au cours des 30 derniers jours)
Brett Baxter
Brett Baxter le 17 Oct 2020
Commenté : Stephen23 le 17 Oct 2020
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?
  1 commentaire
Stephen23
Stephen23 le 17 Oct 2020
To access the structure fieldname dynamically you need the syntax given here:
and to access the contents of the cell array returned by fieldnames you need to use curly braces:

Connectez-vous pour commenter.

Réponse acceptée

Walter Roberson
Walter Roberson le 17 Oct 2020
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.
  1 commentaire
Brett Baxter
Brett Baxter le 17 Oct 2020
Got it, this works for me. Thank you!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Tags

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by