Working with structures : Unrecognized field name

47 Ansichten (letzte 30 Tage)
Baptiste Kraehn
Baptiste Kraehn am 13 Mär. 2023
Kommentiert: Baptiste Kraehn am 14 Mär. 2023
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?

Akzeptierte Antwort

Stephen23
Stephen23 am 13 Mär. 2023
Bearbeitet: Stephen23 am 14 Mär. 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 Kommentare
Stephen23
Stephen23 am 14 Mär. 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 am 14 Mär. 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by