Hi,
Is there any way to convert string with dots do a dot notation?
Let S be a structure, I want to get
I store a "path" to field to a string
path = ['field1.field2.field3'];
I want to get to a specified field3, instead of
S.field1.field2.field3
I want to call it like this, without separating it by dots.
S.(path)
If I put it like this, it treats the whole string like one name of field.
The reason is that I use a loop which creates the string "path", depending on existance of fields in each "depth" - the substructures are inconsistent. I want the "depth" (number of dots) to be variable.
THX

3 件のコメント

Peng Li
Peng Li 2020 年 3 月 31 日
Have you tried eval instead?
eval(['S.' path]);
Vit Krcal
Vit Krcal 2020 年 3 月 31 日
Thanks a lot!
Stephen23
Stephen23 2020 年 4 月 1 日
@Peng Li: due to the disadvantages of eval that approach is not recommended.

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

 採用された回答

Steven Lord
Steven Lord 2020 年 3 月 31 日

2 投票

DON'T use eval. There's no need to use it in this case anyway. split the text representation of the nested fields into pieces then pass those pieces into getfield as a comma-separated list.
S.field1.field2.field3 = 42;
P = 'field1.field2.field3';
pathPieces = split(P, '.');
theAnswer = getfield(S, pathPieces{:})
Things get trickier if you have a more complicated indexing expression, but take a look at the help and documentation for getfield for how to handle such situations.

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeStructures についてさらに検索

製品

リリース

R2019b

質問済み:

2020 年 3 月 31 日

コメント済み:

2020 年 4 月 1 日

Community Treasure Hunt

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

Start Hunting!

Translated by