How to create a structure in which variables can be labelled with a string?
3 views (last 30 days)
Show older comments
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 Comments
Stephen23
on 6 Jun 2016
@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.
Answers (1)
Stephen23
on 31 May 2016
Edited: Stephen23
on 31 May 2016
>> 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 Comment
Jos (10584)
on 31 May 2016
Just to elaborate on this: you can create a variable that holds the name of the label:
TheLabel = 'xxx'
S.(TheLabel).name
See Also
Categories
Find more on Variables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!