MATLAB: Efficient way to find mirror entries

findfor loopMATLAB

Hello,
I have a matrix A with N rows. Any arbitrary row i=1,…,N looks like [a b xi], where a,b are positive integers.
For my purposes, for any two rows i,j, if xi=xj, then [a b xi] is equivalent to [a b xj] and [b a xj] and I want to keep only one of them. Note that the in the last example a and b is 'flipped'.
I can easily screen out the cases [a b xi], [a b xj]
[~,loc,~] = unique(A,'rows');
A = A(loc,:);
This is very quick.
However, then I take care of [a b xi], [b a xj] by
k=0;
temp = zeros(size(A));
for i = 1:size(A,1)
pass = 1;
%discard nodes at the same x, but reverse orientation
for j=1:i
if j~=i && ...
~isequal(A(i,3),A(j,3)) && ...
isequal(A(i,1:2),fliplr(A(j,1:2)))
pass = 0;
end
end
if pass ==1
k = k+1;
temp(k,:) = A(i,:);
end
end
A = temp(1:k,:);
Which is painfully slow (A is quite large).
Can someone suggest a quicker way to do this?
Thank you very much!

Best Answer

A = unique(A, 'rows')
would be even faster than going through loc.
Since the order of a and b does not matter, then the simplest way to remove all duplicates is probably:
unique([sort(A(:, [1 2]), 2), A(:, 3)], 'rows')