Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if a rectangular matrix has duplicate rows in MATLAB?

I have an n-by-m rectangular matrix (n != m). What's the best way to find out if there are any duplicate rows in it in MATLAB? What's the best way to find the indices of the duplicates?

like image 989
Nathan Fellman Avatar asked Mar 24 '10 17:03

Nathan Fellman


People also ask

How do I find unique rows in MATLAB?

C = unique( A ) returns the same data as in A , but with no repetitions. C is in sorted order. If A is a table or timetable, then unique returns the unique rows in A in sorted order.

How do you find the number of rows in a 2d array in MATLAB?

If for example your matrix is A, you can use : size(A,1) for number of rows. size(A,2) for number of columns. Also there are some other ways like : length ( A(:,1) ) for number of rows.


2 Answers

Use unique() to find the distinct row values. If you end up with fewer rows, there are duplicates. It'll also give you indexes of one location of each of the distinct values. All the other row indexes are your duplicates.

x = [
    1 1
    2 2
    3 3
    4 4
    2 2
    3 3
    3 3
    ];
[u,I,J] = unique(x, 'rows', 'first')
hasDuplicates = size(u,1) < size(x,1)
ixDupRows = setdiff(1:size(x,1), I)
dupRowValues = x(ixDupRows,:)
like image 94
Andrew Janke Avatar answered Sep 24 '22 17:09

Andrew Janke


You can use the functions UNIQUE and SETDIFF to accomplish this:

>> mat = [1 2 3; 4 5 6; 7 8 9; 7 8 9; 1 2 3];    %# Sample matrix
>> [newmat,index] = unique(mat,'rows','first');  %# Finds indices of unique rows
>> repeatedIndex = setdiff(1:size(mat,1),index)  %# Finds indices of repeats

repeatedIndex =

     4     5
like image 22
gnovice Avatar answered Sep 23 '22 17:09

gnovice