快速比较两个矩阵的行?

时间:2015-04-13 19:38:33

标签: performance matlab matrix vectorization

我有一个代码,在运行期间重复几次。此代码将C两行的行进行比较。运行需要很长时间,特别是对于大型C。我正在寻找一种快速的方式来运行它。我使用a(ismember(a,b)))代替intersect(a,b)

     I = size (C,1);
     for i = 1 : I-1,
        for j = i+1 : I,
            a=C(i,:);
            b=C(j,:);
            if sum(a(ismember(a,b)))-sum(b)==0,
                n = n+1;
                K(n) = j;
                K1(n) = i;
            end
        end
    end

1 个答案:

答案 0 :(得分:3)

这将是一个vectorized方法 -

%// Get the size of C and pairwise indices
N = size(C,1);
[Y,X] = find(bsxfun(@gt,[1:N]',[1:N])); %//'

%// Form the two pairs
p1 = C(X,:);
p2 = C(Y,:);

%// Get the matches for each element in a row against all other elements in
%// the matching row pair combinations. This would be equivalent to
%// ISMEMBER implementation in the original code
matches = squeeze(any(bsxfun(@eq,permute(p1,[3 2 1]),permute(p2,[2 3 1])),1));
matches = reshape(matches,[],numel(Y)); %//for special case when C has 2 rows

%// Get linear indices that satisfy the equality criteria from original code
idx = find(sum(matches.'.*p1,2) == sum(p2,2)); %//'

%// Store the row and column information from the linear indices
K_vectorized = Y(idx);
K1_vectorized = X(idx);