MATLAB Answers

0

How to remove duplicate rows in a matrix by considering the repeated values in a specific column?

Asked by Gayan Lankeshwara on 23 Oct 2019 at 7:35
Latest activity Commented on by Gayan Lankeshwara on 11 Nov 2019 at 1:00
%% 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 Comments

Sign in to comment.

Tags

Products


Release

R2019a

1 Answer

Answer by Mohammad Sami on 1 Nov 2019 at 8:39
 Accepted Answer

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,:);

  1 Comment

Sign in to comment.