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일

0 개 추천

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

James Tursa
James Tursa 2022년 5월 17일
How do you plan on using this variable downstream in your code? More "eval" statements everytime you want to use it?
DrK
DrK 2022년 5월 17일
That is a good point :-)
I guess that is what it takes, doesn't it?!
Is there a better way to do this?
DrK
DrK 2022년 5월 17일
Actually, I intend to form these structures into a table and later I can access then using the table. I guess this is analogous to the second level of structure that you proposed earlier, but since table was my plan all along, this eval method works better.
Stephen23
Stephen23 2022년 5월 17일
"Is there a better way to do this?"
Yes.
DrK
DrK 2022년 5월 17일
do tell
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일

1 개 추천

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일

0 개 추천

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.

카테고리

제품

릴리스

R2021a

질문:

DrK
2022년 5월 16일

댓글:

DrK
2022년 5월 17일

Community Treasure Hunt

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

Start Hunting!

Translated by