用名称在Matlab循环中变化的矩阵加载do操作 [英] Load an do operations with a matrix whose name varies within a Matlab loop
问题描述
我必须运行一个以 x
索引的Matlab循环.在每次迭代中,我必须加载并使用数组 A_x.mat
,其中下标 x
跟随循环索引.我怎样才能做到这一点?让我给你和例子来突出我的问题.这个例子很愚蠢,但符合我的目的.
I have to run a Matlab loop indexed by x
. At each iteration, I have to load and work with an array, A_x.mat
, where the subscript x
follows the loop index. How can I do that? Let me give you and example to highlight my issue. The example is very silly but serves my purposes.
X=10;
C=cell(X,1)
for x=1:X
load(['A_' num2str(x) '.mat']); %here I load A_x.mat
%C{x}=A_x*3;
end
我不知道如何以允许下标 x
变化的方式计算 A_x * 3
.你能建议吗?
I don't know how to compute A_x*3
in a way that allows the subscript x
to vary. Could you advise?
为了解决我的问题,我也尝试过
To solve my issue I also tried
for x=1:X
B=load(['A_' num2str(x) '.mat']); %here I load A_x.mat and "rename" it B
%C{x}=B*3;
end
但是 B
原来是一个带有1个字段的 1x1
结构,该字段又是 A_x
.因此,我什么都没解决.
but B
turns out to be a 1x1
struct with 1 field that is again A_x
. Hence, I have not solved anything.
推荐答案
您可以将结构子字段名称另存为char并直接使用它访问结构:
You can save the structure subfield name as a char and access the structure with it directly:
X=10;
C=cell(X,1)
for x=1:X
name = ['A_', num2str(x)];
data_structure = load([name, '.mat']); %here I load A_x.mat
C{x} = data_structure.(name) * 3;
end
请注意,您可以使用eval()实现类似的功能,但不建议这样做.如果您需要像这样动态访问变量,请使用结构.
Note that you could achieve something similar with eval() but that is not recommended. If ever you need to access variables dynamically like this, use a structure.
这篇关于用名称在Matlab循环中变化的矩阵加载do操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!