Working with structures : Unrecognized field name

56 visualizzazioni (ultimi 30 giorni)
Hello everyone,
I'm starting to work with Structure array variables and I'm stuck for their use in my function.
I want to get the name of a field in order to use it in a dot product to get data that I use to make my calculations.
So if we take the following example:
s.a.b={'A', 'B', 'C'};
s.a.data={0.125, 0.02, 0, 0, 5, 958, 5.6};
In my case, it is necessary to consider that I obtain the structure "s" without knowing the name of the first field "a", but all other field are known (I work with several sets of structures, this field "a" represents a name that will be different each time for each structure, unlike other fields). The data I need are in the "data" field. So I need to find the name of this field ("a") in order to recover my data by dot product.
I tried to automate the field name search via the "fieldnames()" function, but the result cannot be used in a dot product as I would like.
Field=fieldnames(s);
Dat=s.Field.data
Do you have any ideas on how to get around this problem?

Risposta accettata

Stephen23
Stephen23 il 13 Mar 2023
Modificato: Stephen23 il 14 Mar 2023
"Do you have any ideas on how to get around this problem? "
Field = fieldnames(s);
Dat = s.(Field{1}).data
Note that a better data design might be to use a non-scalar structure, e.g.:
s(1).name = 'WhateverFieldName'
s(1).data = [..]
s(1).b = '...'
s(2).name = 'etcetc.
...
  3 Commenti
Stephen23
Stephen23 il 14 Mar 2023
"I simply added the char() function in order to convert the variable to a character array"
Sorry, I omitted to account for the cell array. Another approach is to use indexing (I modified my answer to show this). In either case you might need to account for having multiple fieldnames.
Baptiste Kraehn
Baptiste Kraehn il 14 Mar 2023
For my application, I know that I will only have a field name in the structure that I extract. But indeed, the code will have to be modified in case it would be possible to have several field names.
Thanks again for your help.

Accedi per commentare.

Più risposte (0)

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!

Translated by