Search code examples
matlabcell-array

multiple cell reference


I have a cell array, lets say C. Each cell contains a matrix.

For example lets say C is

C{1}=[1 2;3 4;5 6]
C{2}=[7 8;9 10;11 12]

How can I create a new cell array D, whose i-th element is a matrix consisted by the i-th transposed rows of all matrices in C?

Then D must be

D{1}=[1 7;2 8]
D{2}=[3 9;4 10]
D{3}=[5 11;6 12]

Solution

  • Given that C is always of the size you have specified, you can try the following rather clumsy solution:

    C{1}=[1 2;3 4;5 6]
    C{2}=[7 8;9 10;11 12]
    
    
    tmp = reshape( [C{:}]', 2,2,3);
    
    D = arrayfun(@(x) squeeze(tmp(:,:,x)), 1:3, 'UniformOutput',  false);
    

    This results in

    >> D{:}
    
    ans =
    
         1     7
         2     8
    
    
    ans =
    
         3     9
         4    10
    
    
    ans =
    
         5    11
         6    12
    

    For matrices of arbitrary size, you can use

    n = length(C);
    [q,p] = size(C{1});
    
    tmp = reshape( [C{:}]', p, n, q);
    
    D = arrayfun(@(x) squeeze(tmp(:,:,x)), 1:n, 'UniformOutput',  false);