Search code examples
arraysmatlabcell-array

Convert a cell array of cells to cell arrays of doubles


Let's say, that i have a cell array of cells containing only numeric values. Its name is Q.

Q = { {[0]    [1]    [0]    [238]} }
Q{1}

ans = 

    [0]    [1]    [0]    [238]

What i would like to do, is to combine all these 4 cells into just one. In that case, it would be something like the one below:

Q{1}

ans =

     0     1     0   238

Any help would be really appreciated.


Solution

  • You have a double-nested cell array:

    Q = { {[0]    [1]    [0]    [238]} }
    

    and you need comma-separated lists to transform it into an array. I assume you have multiple cell arrays within Q, so you can use cellfun:

    out = cellfun(@(x) [x{:}], Q,'uni',0)
    

    and you get

    Q{1} = 
    
        [0]    [1]    [0]    [238]
    
    
    out{1} =
    
         0     1     0   238
    

    For one element this is equivalent to:

    Q{1} = [Q{1}{:}]
    

    as the x in the cellfun operation is equivalent to Q{i} where i is the running variable.

    But if you you just have this one array in your cell array, consider:

    out = cell2mat(Q{:})
    

    as you don't need it to be a cell array at all.