Working with structures : Unrecognized field name
54 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Baptiste Kraehn
el 13 de Mzo. de 2023
Comentada: Baptiste Kraehn
el 14 de Mzo. de 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?
0 comentarios
Respuesta aceptada
Stephen23
el 13 de Mzo. de 2023
Editada: Stephen23
el 14 de Mzo. de 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 comentarios
Stephen23
el 14 de Mzo. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Structures en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!