Search code examples
arraysmatlabindexingcellscell-array

Indexing content of cell array using cell array of indices


The question is: I have a cell array (MyCellArray) and a cell array of indices (IdxCellArray) of the same size, where each cell contains indices for the corresponding cell of MyCellArray.
Is there a way to obtain a cell array output of the elements of MyCellArray indexed by (IdxCellArray)?.
MyCellArray{IdxCellArray} does not work.

To be precise, assume two cases: in the first one I have a cell array with the following structure:

MyCellArray: 2x3
[50x1] [50x1] [50x1]
[76x1] [76x1] [76x1]

IdxCellArray: 2x3
[20x1] [20x1] [20x1]
[21x1] [21x1] [21x1]

Where each IdxCellArray row marks the same indices. i.e. a repmat(IdxCellArray(:,1),1,3) would return exactly IdxCellArray. This is not true for MyCellArray where each cell contains a different vector For the second case I have more generic structures for my arrays:

MyCellArray: 2x3
[53x1] [50x1] [52x1]
[75x1] [71x1] [78x1]

IdxCellArray: 2x3
[11x1] [10x1] [21x1]
[15x1] [18x1] [22x1]

Solution

  • You need cellfun:

    out = cellfun(@(x,y) x(y), MyCellArray, IdxCellArray, 'uni', 0)