dynamic naming of structures

5 ビュー (過去 30 日間)
DrK
DrK 2022 年 5 月 16 日
コメント済み: DrK 2022 年 5 月 17 日
If I have a variable x='name', how can I use x to build a structure with name 'name' that looks like:
name.a
name.b
No need to tell me about the hazards of dynamic variable naming.
Thanks.

採用された回答

DrK
DrK 2022 年 5 月 17 日
Actually, found my own answer:
x = 'name';
eval(sprintf('%s = struct;',x));
This creates a structure named 'name' and one can use the same eval format to add fields to it later.
  7 件のコメント
DrK
DrK 2022 年 5 月 17 日
Thanks for the light reading. I think I am going to take this in the direction of indexing instead.
Thanks again for your help.

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

その他の回答 (2 件)

James Tursa
James Tursa 2022 年 5 月 16 日
Would it be acceptable to use x as a dynamic fieldname instead of the top level variable name? E.g.,
v.(x).a
v.(x).b

DrK
DrK 2022 年 5 月 17 日
Not really. I know about the paranthesis around field names, but it creates another level of structure. The problem is that if I am creating the structure names inside my program, I don't know how to create the structures using those names.
Thanks for your response.

カテゴリ

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

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by