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

48 ビュー (過去 30 日間)
Matthew Saul
Matthew Saul 2015 年 1 月 8 日
回答済み: Image Analyst 2015 年 1 月 18 日
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 件のコメント
Stephen23
Stephen23 2015 年 1 月 8 日
編集済み: Stephen23 2015 年 1 月 18 日
Do not do this. This is poor coding style in MATLAB. See the answers for explanations.

サインインしてコメントする。

採用された回答

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.
Stephen23
Stephen23 2015 年 1 月 11 日
Also using standard MATLAB syntax:
AB1 = struct('a',1, 'b',2, 'c',3);

サインインしてコメントする。

その他の回答 (1 件)

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

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by