Search code examples
matlabcell

How to do intersection of arrays of unknown size which are stored in cells of a matrix?


I have a matrix of cells, call it M. The matrix dimensions are n^3.

Each cell contains an array of indices (a result of a regexp query on some string, not that it matters).

I want to intersect the indices in the arrays in each cell of M.

How can I do that? If I use intersection function how does it know to take the indices from inside the arrays in each cell?

As I understand I have to use cells because the inner arrays are of unknown size.


Solution

  • Is this what you want to do?

    A = M{1};
    for i = 2:numel(M)
      A = intersect(A, M{i});
    end
    

    I don't think there's a neat way to do this using a single intersect call, or with e.g. cellfun.

    If you only want the intersection of specific indices, you can do:

    A = indices(1);
    for i = indices(2:end)
      A = intersect(A, M{i});
    end