Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB: detect and remove mirror imaged pairs in 2 column matrix

I have a matrix

[1 2
 3 6
 7 1
 2 1]

and would like to remove mirror imaged pairs..i.e. output would be either:

[1 2
 3 6
 7 1] 

or

[3 6
 7 1 
 2 1]

Is there a simple way to do this? I can imagine a complicated for loop, something like (or a version which wouldn't delete the original pair..only the duplicates):

for i=1:y
    var1=(i,1);
    var2=(i,2);
    for i=1:y
        if array(i,1)==var1 && array(i,2)==var2 | array(i,1)==var2 && array(i,2)==var1
            array(i,1:2)=[];
        end
    end 
end

thanks

like image 418
user3470496 Avatar asked Jan 20 '16 20:01

user3470496


1 Answers

How's this for simplicity -

A(~any(tril(squeeze(all(bsxfun(@eq,A,permute(fliplr(A),[3 2 1])),2))),2),:)

Playing code-golf? Well, here we go -

A(~any(tril(pdist2(A,fliplr(A))==0),2),:)

If dealing with two column matrices only, here's a simpler version of bsxfun -

M = bsxfun(@eq,A(:,1).',A(:,2)); %//'
out = A(~any(tril(M & M.'),2),:)

Sample run -

A =
     1     2
     3     6
     7     1
     6     5
     6     3
     2     1
     3     4
>> A(~any(tril(squeeze(all(bsxfun(@eq,A,permute(fliplr(A),[3 2 1])),2))),2),:)
ans =
     1     2
     3     6
     7     1
     6     5
     3     4
>> A(~any(tril(pdist2(A,fliplr(A))==0),2),:)
ans =
     1     2
     3     6
     7     1
     6     5
     3     4
like image 63
Divakar Avatar answered Sep 17 '22 10:09

Divakar