# how to check if there are any elements are equal in a vector

187 views (last 30 days)

Show older comments

Dear fellows,

Do you know how to write a code to check if are there any (Given that I don't know the numbers)elements are equal in a vector? And then read the element.

Many thanks, Xueqi

##### 1 Comment

Azzi Abdelmalek
on 10 Jun 2013

Please, make it simple, provide a short example, and tell what should be the result

### Accepted Answer

Jan
on 10 Jun 2013

The question is still not clear. Perhaps you want:

nonZero = x(x ~= 0);

anyDuplicates = length(unique(nonZero)) ~= length(nonZero);

Or equivalently:

anyDuplicates = ~all(diff(sort(x(x ~= 0))));

##### 0 Comments

### More Answers (2)

Daniel Shub
on 10 Jun 2013

There is no built in function that will do that. You could test the number of unique elements in the vector against the length of the vector

f = @(x)isequal(length(x), length(unique(x)))

I am not sure what you mean by read the element, especially if more than one element is duplicated. Maybe something like

y = 1:length(x);

y(sort(b)) = [];

x(y)

Image Analyst
on 10 Jun 2013

### See Also

### Categories

### Community Treasure Hunt

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

Start Hunting!