find duplicates in a vector in matlab

You can use the unique function in MATLAB to find the duplicates in a vector. Here's a code snippet to achieve this:

main.m
vector = [1, 2, 2, 3, 4, 4];
[duplicates,~,index] = unique(vector);
count = accumarray(index(:), 1);
duplicates(count <= 1) = []; % remove non-duplicate elements
162 chars
5 lines

In this code snippet, the first line initializes a vector with some duplicate elements. Then, the unique function is used to find all the unique elements in the vector, as well as their frequencies and indices in the original vector. The accumarray function is then used to count the number of occurrences of each unique element in the original vector. Finally, duplicates are identified as those elements with a frequency greater than 1, and non-duplicate elements are removed.

The variable duplicates contains all the duplicates found in the vector, and can be used for further analysis.

related categories

gistlibby LogSnag