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

조회 수: 39 (최근 30일)
Jodok Waibel
Jodok Waibel 2022년 5월 24일
답변: Jan 2022년 5월 27일
I need a series of 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.
I know this is bad practice and it makes matlab run slowly. However this would help me in my workplace a lot since i have about 1800 sets of data that need to be named in a certain pattern.
Thank you for your help, Jodok.
PS: I am working with release 2020b.
  댓글 수: 1
Stephen23
Stephen23 2022년 5월 24일
편집: Stephen23 2022년 5월 24일
"However this would help me..."
Unlikely.
"... since i have about 1800 sets of data that need to be named in a certain pattern."
Why do they need to be named in a particular pattern? What will you do with them?
Instead of describing the actual problem, you are describing your attempted solution:
Tell us what you are actually trying to achieve, what tools/functions/data you are using. Do not assume a solution.

댓글을 달려면 로그인하십시오.

답변 (2개)

Mustafa Abu-Mallouh
Mustafa Abu-Mallouh 2022년 5월 24일
Instead of defining the variable name with text (as you mentioned, bad practice), would you be able to use a structure instead?
MATLAB lets you generate field names from variable data, see this link for more details:

Jan
Jan 2022년 5월 27일
Read Stephen23's hints carefully, because they are valuable.
Storing important information in the names of variables is a programming anti-pattern. It produces more problems than it solves. Remember, that Matlab replaces variables by simple pointers to the data during the execution of the code, so keeping important details inthe names is a confusing indirection.
Store the information as data instead:
text = 'AB1';
names = sprintfc(['%c', text], 'abc')
names = 1×3 cell array
{'aAB1'} {'bAB1'} {'cAB1'}
data = [1,2,3]
data = 1×3
1 2 3
Now you can work with the names array to identify the index of a specific value of data.
But currently it looks, like the redundant text can be omitted - because it is redundant...

카테고리

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