Working with structures : Unrecognized field name

54 ビュー (過去 30 日間)
Baptiste Kraehn
Baptiste Kraehn 2023 年 3 月 13 日
コメント済み: Baptiste Kraehn 2023 年 3 月 14 日
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?

採用された回答

Stephen23
Stephen23 2023 年 3 月 13 日
編集済み: Stephen23 2023 年 3 月 14 日
"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 件のコメント
Stephen23
Stephen23 2023 年 3 月 14 日
"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 2023 年 3 月 14 日
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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by