Meher81
Meher81

Reputation: 163

Fast way to compare rows of a matrix two by two?

I have a code, repeats several time during running. This code compares the rows of C two by two. It takes long time to run, specially for large C. I am looking for a fast way to run that. I have used a(ismember(a,b))) instead of 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

Upvotes: 1

Views: 119

Answers (1)

Divakar
Divakar

Reputation: 221564

This would be one vectorized approach -

%// 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);

Upvotes: 3

Related Questions