MATLAB: How to convert a numeric cell array with different data types to a matrix in MATLAB 8.1 (R2013a)

arraycellcell2matdatatypeMATLABnonuniform

I have a cell array in which certain cells contain NaNs which are represented as doubles whereas other cells contain numbers represented by single data type. I would like to convert the cell to a matrix to proceed further computations on it however MATLAB does not allow converting cell arrays with different data-types to a matrix.

Best Answer

This conversion could be accomplished using CELLFUN in MATLAB. Matrices in MATLAB are however composed of uniform datatype and hence all the cell contents need to be converted to the same data-type.
The CELLFUN function takes each cell of the cell array, applies the function passed in as an argument and stores the output in the corresponding location of a matrix.
Let us consider an example,
C = {single(1),2; NaN, NaN}
The first cell of C contains a single data-type whereas the rest of the cells contain double data-type.
M = cellfun(@(x) double(x), C)
This function converts the contents of each cell of C to a double and stores them in a matrix M.