フィルターのクリア

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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by