How to create a structure in which variables can be labelled with a string?

조회 수: 8 (최근 30일)
Mr M.
Mr M. 2016년 5월 31일
댓글: Stephen23 2016년 6월 6일
I need a data structure in which there are structs with common fields: xxx.mean, xxx.std, xxx.description, yyy.mean, yyy.std, yyy.description, zzz.mean, zzz.std, zzz.description, etc.
But I want to load/call/get xxx, yyy or zzz by labelling it by a string, so I can change between them by changing the label: mystring = 'xxxname' or mystring = 'yyyname'.
So something like this: 'xxxname'.mean or 'yyyname'.std
  댓글 수: 4
Mr M.
Mr M. 2016년 6월 3일
편집: Stephen23 2016년 6월 6일
Please answer the question. And I dont want dynamically accessing variable names. I want a struct with sting indices or flags. I dont want to change the name! I dont want to create variable names on the fly
Stephen23
Stephen23 2016년 6월 6일
@Mr M.: xxx and yyy are variable names (the fact that they are structures is totally irrelevant). You want to change their names (that is what your question states). Ergo, you want to change variable names.

댓글을 달려면 로그인하십시오.

답변 (1개)

Stephen23
Stephen23 2016년 5월 31일
편집: Stephen23 2016년 5월 31일
Just use one structure S and dynamic fieldnames:
>> S.('xxx').name = 'anna';
>> S.('yyy').name = 'bob';
>> S.('xxx').mean = 100;
>> S.('yyy').mean = -pi;
and access the data in the usual way:
>> S.('xxx').mean
ans = 100
>> S.('xxx').name
ans = anna
See how easy it is?
FYI, what you are proposing is possible but it requires creating and accessing the variables dynamically, which is a very bad way to write code, because it is slow, buggy, and obfuscated:
  댓글 수: 1
Jos (10584)
Jos (10584) 2016년 5월 31일
Just to elaborate on this: you can create a variable that holds the name of the label:
TheLabel = 'xxx'
S.(TheLabel).name

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Variables에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by