MATLAB Answers

Karen Hornsby

Cell2mat - creating a matrix from mismatched cell sizes

Asked by Karen Hornsby
on 16 Jan 2013

Does anyone know how to create a matrix from a cell array where some of the cells have different lengths? Basically my instrument got interrupted when writing it's output file and finished halfway through a line. I don't want to discard the file as it's 99% complete. Is there another command which selectively converts a given sample size of a cell?

  3 Comments

Cedric Wannaz
on 16 Jan 2013

What is the structure of your data (cell array, valid cells content, invalid cells content)?

Karen Hornsby
on 17 Jan 2013

just a plain old cell arry, 1 row and 56 cells all containing doubles.

Matt J
on 17 Jan 2013

If your data is initially acquired as a file, how did it get into cell array form? Why would you import the file to a cell array if you ultimately want it to be a vector?

Products

2 Answers

Answer by Walter Roberson
on 17 Jan 2013
 Accepted answer

No, you cannot do that. So what you do instead is figure out where the smaller lines are and pad those rows with enough NaN to match the size of the other rows. Then you can cell2mat()

  2 Comments

Karen Hornsby
on 17 Jan 2013

What search term would I use to find append to cell?

Walter Roberson
on 17 Jan 2013
prevlen = sum(cellfun(@length, C(end-1,:)));
lastlen = sum(cellfun(@length, C(end,:))));
C{end,end} = [C{end,end}, NaN(1,prevlen - lastlen)];
mat2cell(C)

Answer by Jan Simon
on 17 Jan 2013

What do you want as output for:

C = {[], 1, 1:2}

?

  2 Comments

Karen Hornsby
on 17 Jan 2013

Do you mean that the code above removes row 1 of column 1&2?

Jan Simon
on 17 Jan 2013

No, "C" is a cell, which contains vectors of different length. Simply copy it to the command window and run it. It is exactly what you have explained by:

 ... a cell array where some of the cells have different lengths?

Now you ask us for creating a matrix from such an input. So how should the output look like in this case?


Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply today