How to combine vectors of different lengths in an array of cells into a matrix in MATLAB

How to efficiently combine vectors of an array of cells with different lengths into a matrix, filling the vectors to the maximum length using 0s or NaNs? That would be a good option for cell2mat().

For example, if I have

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

I would like to receive

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];
+3
source share
1 answer

EDIT:

For a row vector cell, as in your case, this will result in 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 formulated somewhat differently, my answer basically does what you want.

, :

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

maxLength . , .

maxLength ,

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

All Articles