Return all unique rows with unique elements

조회 수: 6 (최근 30일)
Daniel
Daniel 2011년 9월 28일
How would I find all rows of a matrix which contain only unique elements? For example, if I have a matrix containing all 3-way combinations of the numbers 1-3:
>> x = allcomb(1:3, 1:3, 1:3)
x =
1 1 1
1 1 2
1 1 3
1 2 1
1 2 2
1 2 3
1 3 1
1 3 2
1 3 3
2 1 1
2 1 2
2 1 3
2 2 1
2 2 2
2 2 3
2 3 1
2 3 2
2 3 3
3 1 1
3 1 2
3 1 3
3 2 1
3 2 2
3 2 3
3 3 1
3 3 2
3 3 3
I could do the following:
y = unique(sort(x, 2), 'rows');
y(y(:,1) == y(:,2) | y(:,1) == y(:,3) | y(:,2) == y(:,3), :) = [];
But is there a more efficient way to accomplish this for matrices with an arbitrary number of columns?
Thanks, Dan

채택된 답변

Daniel
Daniel 2011년 9월 28일
@andrei:
This does not work because it returns several rows which contain the same element. What I am looking for is a matrix of rows which only contain unique elements. In the above example, this is a single row [1 2 3], but in principle could be much larger. As an example, consider the following:
x = allcomb(1:5, 1:5, 1:5);
y = unique(sort(x, 2), 'rows');
y(y(:,1) == y(:,2) | y(:,1) == y(:,3) | y(:,2) == y(:,3), :) = []
Thanks, Dan
[I accidentally hit the accept this answer button. Please disregard.]

추가 답변 (3개)

Andrei Bobrov
Andrei Bobrov 2011년 9월 28일
variant (edited 09/28/2011 13:00 MDT)
xu = unique(x);
[~,loc] = ismember(x,xu);
[a,b] = unique(sort(loc,2),'rows','first');
out = x(b(all(diff(a,1,2),2)),:);
variant 2
[xu,b] = unique(sort(x,2),'rows')
out = x(sort(b(all(diff(xu,1,2),2))),:)

Daniel
Daniel 2011년 9월 28일
@andrei:
Ah, the last line should be:
out = x(b(all(diff(a,1,2),2), :), :);
That does it! Thanks!!

Jan
Jan 2011년 9월 28일
No need for the time-consuming UNIQUE:
x = allcomb(1:3, 1:3, 1:3);
index = all(diff(sort(x, 2), 1, 2), 2);
y = x(index, :);

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by