MATLAB: detect and remove mirrored mapped pairs in a 2-column matrix

I have a matrix

[1 2 3 6 7 1 2 1] 

and would like to remove the mirrored displayed pairs..ie the output will be either:

 [1 2 3 6 7 1] 

or

 [3 6 7 1 2 1] 

Is there an easy way to do this? I can imagine a complex loop, something like (or a version that does not delete the original pair ... only 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

+6
source share
2 answers

How is it 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 we are talking about only two column matrices, here's a simpler version of bsxfun -

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

Run Example -

 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 
+9
source

This is not such a fantastic, but, I hope, understandable and easy manner.

 % Example matrix m = [1 2; 3 6 ; 7 1; 2 1; 0 3 ; 3 0]; 

Comparing m with its inverted version, the ismember function returns a mirror_idx , a 1D vector with each row containing the index of the mirror row, or 0 if none exist.

 [~, mirror_idx] = ismember(m,fliplr(m),'rows'); 

Go through the indices of the mirror lines. If you find one “mirror” line ( mirror_idx > 0 ), set its counter-part as “not mirror image”.

 for ii = 1:length(mirror_idx) if (mirror_idx(ii) > 0) mirror_idx(mirror_idx(ii)) = 0; end end 

Take only lines marked as having no mirror.

 m_new = m(~mirror_idx,:); 

Hello

0
source

All Articles