matlabmatrixreshapecell-array

how to reshape a cell array to matrix in desired size


I have a 2*2 cell array which every element of it is a 2*2 matrix called m1,m2,m3,m4.I want to convert this cell array to a matrix of size 4*4 so that my gernerated matrix will be M=[m1 m2;m3 m4].I have tried using cell2mat function which gives me 2*8 matrix and then reshaping it to 4*4 but this does not work.

Can anyone help me to do this with matlab?

and please give a general code for different size of cell arrays and matrix sizes because in my code based on input number cell array and matrix sizes changes.


Solution

  • cell2mat should work. Depending on what you want, you may need a transpose:

    >> m1 = [1 2; 3 4];
    >> m2 = [11 12; 13 14];
    >> m3 = [21 12; 23 14];
    >> m4 = [31 32; 33 34];
    >> myCell = {m1, m2; m3 m4};
    >> cell2mat(myCell)
    ans =
         1     2    11    12
         3     4    13    14
        21    12    31    32
        23    14    33    34
    >> cell2mat(myCell.')
    ans =
         1     2    21    12
         3     4    23    14
        11    12    31    32
        13    14    33    34