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

48 次查看(过去 30 天)
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

采纳的回答

Stephen23
Stephen23 2015-1-8
编辑:Stephen23 2015-1-8
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 个评论
Adam
Adam 2015-1-8
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.

请先登录,再进行评论。

更多回答(1 个)

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

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by