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.
This is hard to define well, assume you have a tolerance of 1.
Then what would be the outcome of `[1; 2; 3; 4]`? 

When you have multiple columns a definition could become even more challenging.

However, if you are mostly worried about rounding issues, you can solve most of it by one of these two approaches:

1. Round all numbers (considering your tolerance), and then use `unique`
2. Start with the top row as your unique set, use [`ismemberf`](http://www.mathworks.com/matlabcentral/fileexchange/23294-ismemberf) to determine whether each new row is unique and if so, add it to your unique set.

The first approach has the weakness that 0.499999999 and 0.500000000 may not be seen as duplicates. Whilst the second approach has the weakness that the order of your input matters.