Search code examples
matlabnestedcell-array

Access nested cell array


I have a cell array of size 1x84, where the elements are 1x1 or 1x2 cells.

I woluld like to get a cell array of size 1x84 by taking the first element from the nested cells

CellList = <1x84 cell>

CellList  = <1x1 cell>  <1x1 cell>  <1x1 cell>  <1x2 cell>  <1x1 cell> ... <1x2 cell>       

The subelements are also cells


I tried using this code:

CellList = cellfun(@(x)x{1,:}{1,:},CellList, 'UniformOutput',0);

But I faced the following error:

error : Cell contents reference from a non-cell array object.

Solution

  • cellfun accesses each element of the cell you give it, so you are taking an element x, trying to access its first element, and the first element of that which doesn't exist.

    You want to use

    CellList2 = cellfun(@(x)x{1}, CellList, 'uniformoutput', false)
    

    Edit:

    You claim you're still getting an error, in which case your problem is not reproducible. Here is some setup code:

    % define a 1x84 cell array
    c = cell(1,84);
    % Make each element a 1x2 or 1x1 cell array 
    for n = 1:84; c{n} = cell(1,randi([1,2],1)); end;
    % Output is as you've described and shown
    >> c = <1x84 cell>
         = <1x2 cell> <1x1 cell> <1x1 cell> ... <1x2 cell>
    

    Now use my above code, and it works fine.

    d = cellfun(@(x)x{1},c,'uniformoutput',false);
    d = <1x84 cell>
      = [] [] [] [] ... []   % All empty elements as we initialised empty cells