Search code examples
matlabcell-array

How to pool cells while keeping the old cells intact?


I want to create an n x 1 cell array, based on an n x m cell array. I want to operate on each row of the n x m cell array, so that all the cells will be put into a single cell in the new array. e.g. the old one is like this

{'a'}, {'bc'}, {'def'}, {'g'}
{'h'}, {'i'}, {'jk'}, {'lmn'}

the new one is like this

{1x4 cell}
{1x4 cell}

Inside the 1st {1x4 cell}, there are 4 cells {'a'}, {'bc'}, {'def'}, {'g'} and so on. How to do it? I don't want to merge cells so that it becomes {'abcdefg'}.


Solution

  • If your input is a 2D cell array of strings,

    c = {'a', 'bc', 'def', 'g';
         'h', 'i',  'jk',  'lmn'};
    

    the desired output is given by mat2cell (inspite of that function's name, its first input can be any array, not necessarily a matrix):

    result = mat2cell(c, ones(1,size(c,1)), size(c,2));