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 CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by