Question: In Matlab, there is this [`unique` command](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/unique.html) that returns thew unique rows in an array. This is a very handy command.

But the problem is that I can't assign tolerance to it-- in double precision, we always have to compare two elements within a precision. Is there a built-in command that returns unique elements, within a certain tolerance?

Answer: 
**As of R2015a**, there is finally a function to do this, [`uniquetol`](http://www.mathworks.com/help/matlab/ref/uniquetol.html) (**before R2015a**, see [my other answer](https://stackoverflow.com/a/20850949/2778484)):

> 
> `uniquetol` Set unique within a tolerance.  
>   
> 
>      `uniquetol` is similar to `unique`. Whereas `unique` performs exact comparisons, `uniquetol` performs comparisons using a tolerance.
> 
> 
> 

The syntax is straightforward:

> 
> `C = uniquetol(A,TOL)` returns the unique values in `A` using tolerance `TOL`.
> 
> 
> 

As are the semantics:

> 
> Each value of `C` is within tolerance of one value of `A`, but no two elements in `C` are within tolerance of each other. `C` is sorted in ascending order. Two values `u` and `v` are within tolerance if:  
> 
>      `abs(u-v) <= TOL*max(A(:),[],1)`
> 
> 
> 

It can also operate "`ByRows`", and the tolerance can be scaled by an input "`DataScale`" rather than by the maximum value in the input data.

But there is an important note about uniqueness of the solutions:

> 
> There can be multiple valid `C` outputs that satisfy the condition, "no two elements in `C` are within tolerance of each other." For example, swapping columns in `A` can result in a different solution being returned, because the input is sorted lexicographically by the columns. Another result is that `uniquetol(-A,TOL)` may not give the same results as `-uniquetol(A,TOL)`.
> 
> 
> 

There is also a new function `ismembertol` is related to `ismember` in the same way as above.
I've come across this problem before. The trick is to first sort the data and then use the diff function to find the difference between each item. Then compare when that difference is less then your tolerance.
This is the code that I use:

```
tol = 0.001
[Y I] = sort(items(:));
uni_mask = diff([0; Y]) > tol;
%if you just want the unique items:
uni_items = Y(uni_mask); %in sorted order
uni_items = items(I(uni_mask));  % in the original order

```

This doesn't take care of "drifting" ... so something like 0:0.00001:100 would actually return one unique value.

If you want something that can handle "drifting" then I would use histc but you need to make some sort of rough guess as to how many items you're willing to have.

```
NUM = round(numel(items) / 10); % a rough guess
bins = linspace(min(items), max(items), NUM);
counts = histc(items, bins);
unit_items = bins(counts > 0);

```

BTW: I wrote this in a text-editor away from matlab so there may be some stupid typos or off by one errors.

Hope that helps