Search code examples
matlabcell-array

extracting a row from a cell-array


I have a cell-array in which contains some information on how to process some data, like the following:

C = [
    {{1 2 3} true 0 0 5 false}; ...
    {{2 3 4} true 0 0 3 false} ...
]

How can I extract each row into its own cell array to get:

C1 = {{1 2 3} true 0 0 5 false}

Solution

  • To slice a cell array and get a cell array output, you should use round parenthesis

    C1 = C(1,:);
    

    With cell arrays, parentheses will return a subset of that cell array as a cell array, while curly braces will unpack whatever is "inside" the element(s) you're indexing.

    So

    C = {1, 2, 3};
    
    % Brace indexing unpacks the data from "inside" the cell elements
    C{1} = 1         % numeric scalar
    C{[1,2]} = 1, 2  % two unpacked outputs which are numeric scalars
    C{:} = 1, 2, 3   % three unpacked outputs which are numeric scalars
    
    % Parentheses returns a cell array sliced from the original
    C(1) = {1}       % cell element
    C([1,2]) = {1,2} % 1x2 cell array
    C(1,:) = {1,2,3} % 1x3 cell array
    

    You can wrap brace indexing in more braces like {C{1,:}} but all you're doing is unpacking the cell array and then putting it into a new cell array, when you could just take the slice C(1,:).


    The same logic applies to table indexing; parentheses take a slice and retain the original data type while braces get the unpacked contents

    T = table([1;2],{'a';'b'})
      2×2 table
        Var1    Var2 
        ____    _____
         1      {'a'}
         2      {'b'}
    
    T(1,2) = 
      table
        Var2 
        _____
        {'a'}
    
    T{1,2} = {'a'} % cell array
    T{1,1} = 1     % numeric scalar