Delete rows of different permutations of same set
조회 수: 9 (최근 30일)
이전 댓글 표시
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?
댓글 수: 0
채택된 답변
the cyclist
2014년 9월 6일
[~,idx] = unique(sort(A,2),'rows','stable')
A = A(idx,:)
댓글 수: 2
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
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!