Load an do operations with a matrix whose name varies within a Matlab loop

时光总嘲笑我的痴心妄想 提交于 2021-02-10 20:51:28

问题


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

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

but B turns out to be a 1x1 struct with 1 field that is again A_x. Hence, I have not solved anything.


回答1:


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

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.



来源:https://stackoverflow.com/questions/63996794/load-an-do-operations-with-a-matrix-whose-name-varies-within-a-matlab-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!