Search code examples
matlabcell-array

Elegant way of stripping the 1st layer of cell array in MATLAB?


I have a 1x2 cell array a such that

  • a{1, 1} is a 5x1 int array containing [1 2 3 4 5]
  • a{1, 2} is a 5x1 cell array containing 'aa', 'bb', 'cc', 'dd', 'ee'

What is the most elegant way of stripping the first layer, producing a 5x2 cell array as follows?

1 'aa'
2 'bb'
3 'cc'
4 'dd'
5 'ee'

Solution

  • How about:

    % original cell
    a = cell(1,2);
    a{1} = [1 2 3 4 5];
    a{2} = {'aa', 'bb', 'cc', 'dd', 'ee'};
    
    % flattened
    aa = reshape([num2cell(a{1}) a{2}], [], 2)