Search code examples
matlabmatrixcell-array

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


How to efficiently combined cell array vectors with different length into a matrix, filling the vectors to max length with 0s or NaNs? It would be a nice option for cell2mat().

For example, if I have

C = {1:3; 1:5; 1:4};

I'd like to get either

M = [1 2 3 0 0
     1 2 3 4 5
     1 2 3 4 0];

or

M = [1 2 3 NaN NaN
     1 2 3 4 5
     1 2 3 4 NaN];

Solution

  • EDIT:

    For a cell of row vectors as in your case, this will pad vectors with zeros to form a matrix

    out=cell2mat(cellfun(@(x)cat(2,x,zeros(1,maxLength-length(x))),C,'UniformOutput',false))
    
    out =
    
         1     2     3     0     0
         1     2     3     4     5
         1     2     3     4     0
    

    A similar question was asked earlier today, and although the question was worded slightly differently, my answer basically does what you want.

    Copying the relevant parts here, a cell of uneven column vectors can be zero padded into a matrix as:

    out=cell2mat(cellfun(@(x)cat(1,x,zeros(maxLength-length(x),1)),C,'UniformOutput',false));
    

    where maxLength is assumed to be known. In your case, you have row vectors, which is just a slight modification from this.

    If maxLength is not known, you can get it as

    maxLength=max(cellfun(@(x)numel(x),C));