4

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];
yuk
  • 19,098
  • 13
  • 68
  • 99
  • 1
    Duplicate of [How can I accumulate cells of different lengths into a matrix in MATLAB?](http://stackoverflow.com/questions/3054437/how-can-i-accumulate-cells-of-different-lengths-into-a-matrix-in-matlab) – gnovice Jun 02 '11 at 04:57
  • Yes! Thanks. Unfortunately I failed to find it. – yuk Jun 02 '11 at 05:22

1 Answers1

3

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));
Community
  • 1
  • 1
abcd
  • 41,765
  • 7
  • 81
  • 98
  • Thanks, @yoda. You almost made the one-liner code comparing with previous question. Unfortunately the first line does not work. And I'd change the maxLength finder to a simpler one: `maxLength = max(cellfun(@numel,x));` I'll look more into it. – yuk Jun 02 '11 at 05:39
  • @yuk: Why doesn't it work? As I mentioned, I wrote that for _column_ vectors, whereas you have row vectors here... If you make that change, it should work. I'll edit my question in a couple of minutes to add that in. – abcd Jun 02 '11 at 05:42