循环在字符串的数组上创建变量

发布于 2025-02-06 19:57:11 字数 791 浏览 1 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文