Getting variables name from char array

조회 수: 65 (최근 30일)
Mohamed Salah
Mohamed Salah 2020년 5월 11일
편집: Ameer Hamza 2020년 5월 11일
assuming I have a char array like x
a1=[1 2 3 4];
a2=[10 11 15 11];
b2=[4 5 6 7];
c2=[8 9 10 11];
x=['a1' 'a2' 'b2' 'c2']
assuming I have data like this, how can I make the char in x be treated like the variable name meaning that ('a1' --> a1 == [1 2 3 4])
Notes: - All the variables are created before the char array
- I have to name the variables like (a1,a2,..etc.)
-I have a large number of variables

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 5월 11일
편집: Ameer Hamza 2020년 5월 11일
Short answer: don't used these variable names: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval, instead use a 2D array or a cell array.
The next best thing to do it to use 'a1', 'a2', ..., 'a3' as filednames of the struct. For example
myStruct.a1=[1 2 3 4];
myStruct.a2=[10 11 15 11];
myStruct.b2=[4 5 6 7];
myStruct.c2=[8 9 10 11];
x={'a1' 'a2' 'b2' 'c2'}; % you need a cell array here. The code line in your question will not work
Access them like this
>> myStruct.(x{1}) % same as myStruct.a1
ans =
1 2 3 4
>> myStruct.(x{3})
ans =
4 5 6 7
As a last resort. If you are insistent on using these variable names, then use eval(): https://www.mathworks.com/help/matlab/ref/eval.html or evalc(): https://www.mathworks.com/help/releases/R2020a/matlab/ref/evalc.html
a1=[1 2 3 4];
a2=[10 11 15 11];
b2=[4 5 6 7];
c2=[8 9 10 11];
x={'a1' 'a2' 'b2' 'c2'}; % you need a cell array here. The code line in your question will not work
Access them using eval
>> eval(x{1})
a1 =
1 2 3 4
>> eval(x{4})
c2 =
8 9 10 11

추가 답변 (1개)

Simon Philipp Hehenberger
Simon Philipp Hehenberger 2020년 5월 11일
Create a struct for your data.
You can dynamically create fields in your struct with
For example:
for ii=1:4
samplestruct.(['a' num2str(ii)])=fielddata;
end
creates four fields in the struct 'samplestruct', named 'a1',..,'a4'.

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by