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

68 Ansichten (letzte 30 Tage)
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 Kommentar
Stephen23
Stephen23 am 8 Jan. 2015
Bearbeitet: Stephen23 am 18 Jan. 2015
Do not do this. This is poor coding style in MATLAB. See the answers for explanations.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephen23
Stephen23 am 8 Jan. 2015
Bearbeitet: Stephen23 am 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 Kommentare
Adam
Adam am 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.
Stephen23
Stephen23 am 11 Jan. 2015
Also using standard MATLAB syntax:
AB1 = struct('a',1, 'b',2, 'c',3);

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

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

Kategorien

Mehr zu Variables finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by