0
votes

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.

2

2 Answers

0
votes

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
0
votes

Haybert,

Am I correct in assuming that what you're calling M is actually c from your last post? The problem is that c is a 2x2 cell array where each element is 1x4.

If we modify what I posted there. And have M be the shape you want each submatrix (M be a 2x2 cell array with 2x2 sub-matrices). Note I modified the definition of c. We can get what you want.

M = reshape(arrayfun(@(i) randi(100, 2, 2), 1:4, 'uni', 0), 2,2);
c = cellfun(@(x) reshape(x, size(M)), reshape(num2cell(cell2mat(cellfun(@(m) m(:), M(:)', 'uni', 0)), 2), size(M{1})), 'uni', 0);
cMatrix = cell2mat(c);