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

Learn moreOpportunities for recent engineering grads.

Apply Today
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?

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

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}

?

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?

## 3 Comments

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/59023#comment_123041

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

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/59023#comment_123204

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

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/59023#comment_123233

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?