How to Call a Variable by Matching String Input

18 views (last 30 days)
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 Comments
Todd
Todd on 11 Jun 2020
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 on 19 Jun 2020
Got it to work with a large struct, thanks!

Sign in to comment.

Accepted Answer

Steven Lord
Steven Lord on 11 Jun 2020
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)

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!