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

To resolve issues starting MATLAB on Mac OS X 10.10 (Yosemite) visit: http://www.mathworks.com/matlabcentral/answers/159016

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?

Karen Hornsby

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)
Walter Roberson
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?

Jan Simon

Contact us