Delete rows of different permutations of same set
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Tom
am 6 Sep. 2014
Kommentiert: the cyclist
am 9 Mär. 2016
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 Kommentare
Akzeptierte Antwort
the cyclist
am 6 Sep. 2014
[~,idx] = unique(sort(A,2),'rows','stable')
A = A(idx,:)
2 Kommentare
the cyclist
am 9 Mär. 2016
"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.
Weitere Antworten (1)
Geoff Hayes
am 6 Sep. 2014
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 Kommentare
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!