Find set intersection of multiple arrays in MATLAB

前端 未结 2 634
不知归路
不知归路 2021-01-23 05:16

I tried to solve this problem, but I could not implement. Could you help me anything for this?

Problem

Mat1 | Mat2 | Mat3

 1 2 | 1 3  |         


        
2条回答
  •  时光取名叫无心
    2021-01-23 05:51

    Here an alternative solution (which seems to run faster than Gunther's) using MATLAB's intersect:

    Mat = {[1 2; 1 3; 2 4; 3 1; 4 5],
           [1 3; 2 6; 3 1; 3 5],
           [2 6; 2 5; 3 1; 5 2]};
    
    result = zeros(sum(cellfun(@(x)size(x, 1), Mat)), 3); % # Preallocate memory
    k = 1;
    for cc = transpose(nchoosek(1:numel(Mat), 2))
        x = intersect(Mat{cc}, 'rows');                   % # Find intersection
        y = ones(size(x, 1), 2) * diag(cc);               % # Generate matrix indices
        result(k:k + numel(y) - 1, :) = [[x; x], y(:)];
        k = k + numel(y);
    end
    
    result(all(~result, 2), :) = [];                      % # Discard zero rows
    result = unique(result, 'rows');                      % # Discard repeated rows
    

    The matrix result should now contain the unique intersection rows and their corresponding matrix indices, just like you want:

    result =   
         1     3     1
         1     3     2
         2     6     2
         2     6     3
         3     1     1
         3     1     2
         3     1     3
    

提交回复
热议问题