Select unique couples from two vectors (?)

조회 수: 8 (최근 30일)
Alessandro Masullo
Alessandro Masullo 2013년 12월 7일
댓글: Alessandro Masullo 2013년 12월 7일
Hello!
I have a code I would like to perform withouth for loop, but I don't know how to describe it, so I'll show you with an example :)
I have two vectors, v1 and v2:
1 7
4 2
6 8
2 4
7 1
8 6
These vectors represent the couples: 1<>7, 4<>2, etc. The couple 1<>7 is the same as 7<>1, but each vector contains all the elements, so all the couple are repeated twice.
I would like to remove the duplicated couples, no matter about the order.
I actually do this with a for loop, but for big vectors it is very slow:
v1f = v1(1);
v2f = v2(1);
for i = 1:numel(v1)
if isempty(intersect(v2(i), v1f))
v1f(i) = v1(i);
v2f(i) = v2(i);
end
end
v1f = v1f(v1f>0);
v2f = v2f(v2f>0);
How can I do it in a faster and nicer way? Thank you.

채택된 답변

Walter Roberson
Walter Roberson 2013년 12월 7일
v = [v1, v2];
v = sort(v, 2);
[uniquerows, idx] = unique(v, 'rows');
uniquev1 = v1(idx);
uniquev2 = v2(idx);
  댓글 수: 1
Alessandro Masullo
Alessandro Masullo 2013년 12월 7일
Thank you! Maybe I should stop programming after midnight :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by