필터 지우기
필터 지우기

Delete rows of different permutations of same set

조회 수: 12 (최근 30일)
Tom
Tom 2014년 9월 6일
댓글: the cyclist 2016년 3월 9일
Say I have an mx4 matrix A. The rows of A contain different digits from 0-9, but many of them have the digits in a different order. I'd like to have Matlab find all of the rows with the exact same digits and then delete all but one. In other words, I want to delete all but one permutation of each set of digits.
For example, say:
A = [5 8 3 2
5 8 2 3
5 3 8 2
7 1 2 3
7 1 3 2]
The result should be:
A = [5 8 3 2
7 1 2 3]
or similar. Is there an easy way to implement this?

채택된 답변

the cyclist
the cyclist 2014년 9월 6일
[~,idx] = unique(sort(A,2),'rows','stable')
A = A(idx,:)
  댓글 수: 2
Triveni
Triveni 2016년 3월 9일
Can you explain me about stable?
the cyclist
the cyclist 2016년 3월 9일
"stable" means that the unique elements in the output will be in the same order as they first appear in the input array. Full details in the documentation for the unique function.

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

추가 답변 (1개)

Geoff Hayes
Geoff Hayes 2014년 9월 6일
Tom - there are probably different ways to implement this, with one solution being to just loop over every row of A and compare with each subsequent one, removing those rows whose intersection includes all elements from both rows. We could use intersect to do that.
atRow = 1;
numRows = size(A,1);
numCols = size(A,2);
while atRow<numRows
rowsToDelete = [];
for k=atRow+1:numRows
if numel(intersect(A(atRow,:),A(k,:)))==numCols
% flag this row for deletion
rowsToDelete = [rowsToDelete; k];
end
end
% delete rows if we have any to delete
if ~isempty(rowsToDelete)
A(rowsToDelete,:) = [];
numRows = size(A,1);
end
% move to the next row
atRow = atRow + 1;
end
On each iteration of the while loop, we reset the array of rows to delete and then we compare the current row with all that follows. If the intersection of any of these two rows is equal to the number of columns in that row, then the rows are identical and we flag that row to delete. At the end of the for loop we check to see if there are any rows to delete. If so, we delete them (by setting their row to the empty matrix) and re-count the number of rows in A. Finally, we move to the next row.

카테고리

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