Search code examples
matlabmatrixconcatenationcell-array

How to combine matrix of different size in a cell array into a matrix in MATLAB


Similarly to How to combine vectors of different length in a cell array into matrix in MATLAB I would like to combine matrix having different dimension, stored in a cell array, into a matrix having zeros instead of the empty spaces. Specifically, I have a cell array {1,3} having 3 matrix of size (3,3) (4,3) (4,3):

A={[1 2 3; 4 5 6; 7 8 9]  [1 2 3; 4 5 6; 7 8 9; 9 9 9]  [1 2 3; 4 5 6; 7 8 9; 4 4 4]}

and I would like to obtain something like:

B =

 1     2     3     1     2     3     1     2     3
 4     5     6     4     5     6     4     5     6
 7     8     9     7     8     9     7     8     9
 0     0     0     9     9     9     4     4     4

I tried using cellfun and cell2mat but I do not figure out how to do this. Thanks.


Solution

  • I would be surprised if this is possible in one or a few lines. You will probably have to do some looping yourself. The following achieves what you want in the specific case of incompatible first dimension lengths:

    A={[1 2 3; 4 5 6; 7 8 9]  [1 2 3; 4 5 6; 7 8 9; 9 9 9]  [1 2 3; 4 5 6; 7 8 9; 4 4 4]}
    
    maxsize = max(cellfun(@(x) size(x, 1), A));
    B = A;
    for k = 1:numel(B)
        if size(B{k}, 1) < maxsize
            tmp = B{k};
            B{k} = zeros(maxsize, size(tmp,1));
            B{k}(1:size(tmp,1),1:size(tmp,2)) = tmp;
        end
    end
    
    B = cat(2, B{:});
    

    Now B is:

    B =
    
         1     2     3     1     2     3     1     2     3
         4     5     6     4     5     6     4     5     6
         7     8     9     7     8     9     7     8     9
         0     0     0     9     9     9     4     4     4