smörkex
smörkex

Reputation: 336

MATLAB Efficiently find the row that contains two of three elements in a large matrix

I have a large matrix, let's call it A, which has dimension Mx3, e.g. M=4000 rows x 3 columns. Each row in the matrix contains three numbers, eg. [241 112 478]. Out of these three numbers, we can construct three pairs, eg. [241 112], [112 478], [241 478]. Of the other 3999 rows:

Here's a function that accomplishes this, but is very slow - I'd like to know if there is a more efficient way. Thanks in advance!

M=size(A,1); % no elements

B=zeros(M,3);

for j=1:M
   l=1;
   k=1;
   while l<4 % there cant be more than 3
      if k~=j
         s=sum(ismember(A(j,:),A(k,:)));
         if s==2
            B(j,l)=k;
            l=l+1;
         end
   end
   k=k+1;
end

Upvotes: 0

Views: 284

Answers (1)

bla
bla

Reputation: 26069

For loops are not needed, just use ismember the following way:

 row_id1=find(sum(ismember(M,[241 112]),2)>1);
 row_id2=find(sum(ismember(M,[478 112]),2)>1);
 row_id3=find(sum(ismember(M,[478 241]),2)>1);

each row_id will give you the row index of the pair in that line regardless of the order at which it appears.

The only assumption made here is that one of the pair numbers you look for will not appear twice in a row, (i.e. [112 333 112]). If that assumption is wrong, this can be addressed using unique.

Upvotes: 2

Related Questions