Search code examples
arraysmatlabcell-array

Matlab: Convert cell array of cells into a single cell array


I have, D is a cell array of mismatched cell arrays of strings

A = 

{'abc'; 

'acd' ;

'aaa'}


B = 

{'baa' ;

'bbb'}


C = 

{'acc';

'aaa';

'aad'}

D = { {A}, {B}, {C}}

A, B and C are of different in size and I do not know their size in the first place, so I combined them into D. How do i convert D into a single cell array so that i can write them into an excel sheet?

i.e.

D = 
{'abc' 'baa' 'acc';

'acd' 'bbb' 'aaa';

'aaa' ' '   'aad'}

Solution

  • You can let MATLAB expand the cell array when needed:

    F={}; 
    for k = 1:numel(D), 
        F(1:numel(D{k}), end+1)=D{k}; 
    end
    

    which results in

    F = 
        'abc'    'baa'    'acc'
        'acd'    'bbb'    'aaa'
        'aaa'       []    'aad'
    

    If it is important to have empty matrices as empty strings, use

    >> F(cellfun('isempty', F))={''}
    F = 
        'abc'    'baa'    'acc'
        'acd'    'bbb'    'aaa'
        'aaa'    ''       'aad'