Search code examples
matlabloopsfor-loopmatrixmat

How to call .mat files with different index number from workspace in loop?


I have more than 30, 2D mat files name as A1, A2, A3,.... A30 in workspace. In order to create a 3D mat file how to call A1, A2,... in loop.

for i=1:30  
    A(:,:,i)=A{i}     
end

I want to make A{i} vary as A1,A2,A3,.. in the successive loop.


Solution

  • You can use the evil eval, in combination with sprintf. That way you avoid using loops:

    A1 = 1:3;A2 = 4:6; A3 = 10:12;
    A = eval(['[',sprintf('A%i;',1:3),']'])
    A =    
         1     2     3
         4     5     6
        10    11    12
    

    The sprintf part creates a string A1;A2;A3;, like this:

    sprintf('A%i;',1:3)
    ans =    
    A1;A2;A3;
    

    Then, put brackets around it (it's still a string):

    ['[',sprintf('A%i;',1:3),']']
    ans =
    [A1;A2;A3;]
    

    Finally, evaluate the string:

    eval(['[',sprintf('A%i;',1:3),']'])
    

    To work with 3D:

    A1 = magic(3);A2=2*magic(3);A3=3*magic(3);
    A = permute(reshape(eval(['[',sprintf('A%i;',1:3),']'])',3,3,[]),[2 1 3])
    % or:
    A = permute(reshape(eval(['[',sprintf('A%i;',1:3),']']),3,3,[]),[1 3 2])    
    A(:,:,1) =    
         8     1     6
         3     5     7
         4     9     2        
    A(:,:,2) =    
        16     2    12
         6    10    14
         8    18     4    
    A(:,:,3) =    
        24     3    18
         9    15    21
        12    27     6
    

    Up to the eval part, it's identical. Now, you need to reshape the transposed matrix so that it becomes a 3D matrix. Thereafter, you need to permute it, to switch the first and second dimension.


    Note that you should try to avoid this. The readability is crap, the performance is crappier and the robustness is crappiest. If possible, you should definitely try to avoid the names A1, A2, A3 ....