Search code examples
matlabcell

Convert cell array with sub cells into numeric array


Assume I have A that is a 64x1 cell array.

Each of the 64 cells contains another cell with a string (which is a number, i.e. 11)

A{1, 1}{1, 1} = ’11’ (char)
A{2, 1}{1, 1} = ’13’ (char)

How can I create a numeric array such as

A = [11,13,…]

The cell2mat function seems to work only on “first level” cell array: cell2mat does not support cell arrays containing cell arrays or objects.


Solution

  • You can use cellfun to convert the contents of each individual cell in A to doubles.

    A{1, 1}{1, 1} = '11';
    A{2, 1}{1, 1} = '13';
    
    A_array = cellfun(@(a) str2double(a), A)
    

    Breakdown of the function: @(a) passes the contents of each cell of A to the variable a, which can be converted to doubles using str2double(a).