Find which columns have duplicates

Hey there,
Im writing a code where I have to find which columns of an array have duplicates in them.
I already have found a way to find rows with duplicates but I'm not sure how to make this for columns.
Considering the following: A is a 2d matrix
A = [7 3 1 4 9 8 5 6
9 6 5 8 2 3 7 4
8 5 7 6 3 1 9 2
6 1 9 7 8 4 2 3
3 2 6 5 4 9 1 7
4 9 2 3 1 4 8 5
5 8 3 2 6 7 4 1
1 7 4 9 5 2 3 8];
RowsWithDuplicates = find(arrayfun(@(i)(~isequal (length (unique (A(i,:))), size(A,2))), 1:size(A,1)))
RowsWithDuplicates = 6
I'm not sure how this exactly works but it does.
How can I make it so it finds which columns have duplicates?

답변 (1개)

Torsten
Torsten 2022년 12월 8일

0 개 추천

Transpose the matrix :-)
Or:
ColumnsWithDuplicates = find(arrayfun(@(i)(~isequal (length (unique (A(:,i))), size(A,1))), 1:size(A,2)))

댓글 수: 2

Jochem
Jochem 2022년 12월 8일
Thanks this works!
Rik
Rik 2022년 12월 8일
Just to provide the commentary:
The arrayfun will run the function on the input data, in this case the vector 1:size(A,1).
The function takes a scalar input i, and compares length(unique(A(i,:))) to size(A,2). So it counts the number of elements after unique has done its thing. If those two are the same, that means there are no duplicates. The isequal function will test this.
The last step is that the find function will convert this logical vector to row indices.
The code that Torsten posted just swapped all rows and columns.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

질문:

2022년 12월 8일

댓글:

Rik
2022년 12월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by