Delete rows of different permutations of same set

5 次查看(过去 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?

采纳的回答

the cyclist
the cyclist 2014-9-6
[~,idx] = unique(sort(A,2),'rows','stable')
A = A(idx,:)
  2 个评论
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 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by