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
  댓글 수: 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 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