How can I get a variable name to include a specified string of text?

42 views (last 30 days)
I need multiple variable names to have the same text included in the name. Is there a way to do this? For example, I want something like:
text='AB1'
aAB1=1;
bAB1=2;
cAB1=3;
But rather than writing AB1 I want to call text and have that insert AB1 into the variable name. Basically a(text) is aAB1 and b(text) is bAB1.
This may seem like a waste of time as it would be quicker to type AB1 each type rather than evaluating text, but I will be copying the same code multiple times and I want to only change text each time rather than the names of all the variables. Thanks, Matt
  1 Comment
Stephen23
Stephen23 on 8 Jan 2015
Edited: Stephen23 on 18 Jan 2015
Do not do this. This is poor coding style in MATLAB. See the answers for explanations.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 8 Jan 2015
Edited: Stephen23 on 8 Jan 2015
Basically you should not do this. Using dynamically defined variable names or encoding data within the variable name is a pretty bad idea in MATLAB, as is described on many threads on MATLAB Answers:
The first of these links gives an excellent alternative, which is what you should probably be using for your data: structures . In particular you can dynamically assign the field names, as this example shows:
>> A.title = 'My Data'; % not dynamically set
>> A.data = [1,2,3]; % not dynamically set
>> A.('any_name') = 'this fieldname has been set dynamically';
You should read these:
  2 Comments
Adam
Adam on 8 Jan 2015
To add to that, either:
AB1.a = 1;
AB1.b = 2;
AB1.c = 3;
or
AB1 = containers.Map( { 'a', 'b', 'c' }, [1, 2 3] );
AB1('a')
ans =
1
would work better for your example than individually named variables. Obviously there may be better ways too depending what you really want these variables for.
A simple array is usually the best approach when all the values being assigned are of the same type and just index into it numerically. The map above works the same except your indices are strings 'a', 'b', 'c' or whatever other string you want instead.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 18 Jan 2015
For more information on why that is a bad thing to do, see the FAQ.

Categories

Find more on Characters and Strings 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!