Search code examples
matlabcell-array

Fastest way of finding repeated values in different cell arrays of different size


The problem is the following:

I have a cell array of the form indx{jj} where each jj is an array of 1xNjj, meaning they all have different size. In my case max(jj)==3, but lets consider a general case for the shake of it.

How would you find the value(s) repeated in all the jj i the fastest way?

I can guess how to do it with several for loops, but is there a "one (three?) liner"?

Simple example:

indx{1}=[ 1 3 5 7 9];
indx{2}=[ 2 3 4 1];
indx{3}=[ 1 2 5 3 3 5 4];


ans=[1 3];

Solution

  • Almost no-loop approach (almost because cellfun essentially uses loop(s) inside it, but it's effect here is minimal as we are using it to find just the number of elements in each cell) -

    lens = cellfun(@numel,indx);
    
    val_ind = bsxfun(@ge,lens,[1:max(lens)]');
    vals = horzcat(indx{:});
    
    mat1(max(lens),numel(lens))=0;
    mat1(val_ind) = vals;
    
    unqvals = unique(vals);
    out = unqvals(all(any(bsxfun(@eq,mat1,permute(unqvals,[1 3 2]))),2));