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?


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

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

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?


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()


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

prevlen = sum(cellfun(@length, C(end-1,:)));
lastlen = sum(cellfun(@length, C(end,:))));
C{end,end} = [C{end,end}, NaN(1,prevlen - lastlen)];

Answer by Jan Simon
on 17 Jan 2013

What do you want as output for:

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



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

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?

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!