How to remove duplicate rows in a matrix by considering the repeated values in a specific column?
97 次查看(过去 30 天)
显示 更早的评论
%% consider the following example.
A = [1 2 4; 3 5 7;1 5 8; 2 9 4]
In matrix A, column 1 has a duplicate value which is 1. I need to keep the first met value and remove the rest accordingly. At the same time, the indices of non-duplicates should not be changed.
The possible solution should be,
A_without_dup = [1 2 4;3 5 7;2 9 4]
%% only the final row is removed because a duplicate is found in that row based on the value of column 1 in A.
Thanks.
0 个评论
采纳的回答
Mohammad Sami
2019-11-1
You can use the unique function to return you the index of the unique values in the first column.
Use the stable keyword so the order is preserved. You can then use the index to keep the unique rows.
[~,uidx] = unique(A(:,1),'stable');
A_without_dup = A(uidx,:);
3 个评论
David Linsenbardt
2021-1-12
You can also combine rows w/ stable and remove rows where duplicates exist in multiple columns:
[~,uidx] = unique(data(:,[1 2]),'rows','stable');
data = data(uidx,:);
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!