Star
Star

Reputation: 2299

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

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.

Upvotes: 1

Views: 59

Answers (1)

Joseph
Joseph

Reputation: 663

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.

Upvotes: 3

Related Questions