In Matlab, I want to create a series of variables based on an array of strings.
As a simplified example, from the given matrixes A1, A2, B1, and B2, I want to create variables A and B as their corresponding combined matrixes. Kindly teach me how to do that. It is very much appreciated.
I have tried the below code, which does not work.
% Simplified examples of given matrixes
A1 = [1;2];
A2 = [3;4];
B1 = [5;6];
B2 = [7;8];
% What I need
ATest = cat(1, A1, A2);
BTest = cat(1, B1, B2);
% I have many of A, B, …, thus looking for a loop of string array, but below trying does not work.
VarList = {'A', 'B'};
for ivar = 1:length(VarList)
eval(['%d = cat(1, %d1, %d2);', VarList(ivar)));
end
Added: (a temporary
solution for my desire). Note the use of VarList{ivar}
instead of VarList(ivar)
. I should note it as temporary since caution (for the problem of dynamic variables) may be needed.
VarList = {'A', 'B'};
for ivar = 1:length(VarList)
v = VarList{ivar};
eval([v '=cat(1,' v '1,' v '2);']);
end