How to Call a Variable by Matching String Input
18 ビュー (過去 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
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
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 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!