循环在字符串的数组上创建变量
在MATLAB中,我想根据一系列字符串创建一系列变量。
作为一个简化的示例,从给定的矩阵A1,A2,B1和B2中,我想创建变量A和B作为其相应的组合矩阵。请教我如何做。非常感谢。
我尝试了以下代码,该代码不起作用。
% 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
添加:( 临时
解决方案为我的愿望)。注意varlist {ivar}
而不是varlist(ivar)
的使用。我应该注意到它是暂时的,因为可能需要谨慎(对于动态变量的问题)。
VarList = {'A', 'B'};
for ivar = 1:length(VarList)
v = VarList{ivar};
eval([v '=cat(1,' v '1,' v '2);']);
end
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论