How to Call a Variable by Matching String Input

조회 수: 18 (최근 30일)
Matthew Cousins
Matthew Cousins 2020년 6월 11일
댓글: Matthew Cousins 2020년 6월 19일
I have the following information currently in my code:
Groups = {'A', 'B', 'C'}
A = {'1','2','3'}
B = {'4','5','6'}
C = {'7','8','9'}
I am creating two variables of class struct (data_left and data_right) based on a certain mathematical formula. aF is the particular field name, and m is the index of the value in that specific field.
for iF = 1:length(Groups)
aF = Groups{iF};
for m = 1:length(data_left.(aF))
data_left. (aF) (m) = (formula)
data_right. (aF) (m) = (formula)
if indiv_SBscore_right. (aF) (m) < 0
group = convertCharsToStrings(aF);
f = msgbox('Recheck Group: ' + group,'Possible Error Detected')
The purpose of the final three lines is to detect if that value is negative, and if so return information on which value was negative. It currently works so that the name of the group is identified. If possible, I would like to find a way to call variable A, B, or C, depending on where the negative value is found.
For example, if data_left.B (1) is negative, I would like to call B{1} and return '4'. If data_right.C (3) is negative, I would like to call C{3} and return '9'. This would allow me to replace the last line to read
'Recheck 4','Possible Error Detected'
or
'Recheck 9','Possible Error Detected'
  댓글 수: 2
Todd
Todd 2020년 6월 11일
You could use eval
aF = "B";
m = 1;
eval(aF + num2str(m,"{%d}"))
Or, if aF is a char array,
eval([aF num2str(m,"{%d}")])
But eval should be avoided if possible. Alternately, you could but A, B, and C in a struct
group.B = {'4','5','6'};
group.(aF){m}
Matthew Cousins
Matthew Cousins 2020년 6월 19일
Got it to work with a large struct, thanks!

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

채택된 답변

Steven Lord
Steven Lord 2020년 6월 11일
Use a struct array or a table array. Since Todd showed the struct approach in a comment, I'll show the table approach.
Groups = {'A', 'B', 'C'}
A = {'1','2','3'}
B = {'4','5','6'}
C = {'7','8','9'}
T = table(A.', B.', C.', 'VariableNames', Groups)
T{2, 'B'} % {'5'}
T.B % Equal to B
Though since you're using release R2018b you could store your data as string arrays.
SA = ["1"; "2"; "3"];
SB = ["4"; "5"; "6"];
SC = ["7"; "8"; "9"];
T2 = table(SA, SB, SC, 'VariableNames', Groups)
T2{2, 'B'} % "5"
% or
M = reshape(1:9, [3 3]);
T3 = array2table(string(M), 'VariableNames', Groups)

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by