How to Call a Variable by Matching String Input

19 次查看(过去 30 天)
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}

请先登录,再进行评论。

采纳的回答

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