possible bug in "unique" function

11 views (last 30 days)
jenka
jenka on 29 Sep 2011
Commented: Peter Perkins on 1 Dec 2015
Dear all,
Could you, guys, help me please. I have a matrix
X =
2.2000 3.3000
2.2000 3.3000
4.0000 5.0000
3.0000 5.0000
So I would like to find matrix A with unique rows in it.
So I use A=unique(X,'rows'). I get:
A =
2.2000 3.3000
3.0000 5.0000
4.0000 5.0000
Which is great. Then I go to my larger example. The size is 675041x2. I run the same line A=unique(X,'rows') as above. However, it does not give me unique numbers it has a lot of rows that are repeated. Grrrr. Moreover, I expect the first row in X to be equal to the first row in A. But in my case, it is not. Any suggestions please. The only thing I can think of is the truncation of floats. For example, the first element in my original X matrix is equal to:
X(1,:)
ans =
1.0e+06 *
1.2123 0.9458
Not sure at all

Answers (4)

Walter Roberson
Walter Roberson on 29 Sep 2011
format long g
X(1,:) - A(1,:)

the cyclist
the cyclist on 29 Sep 2011
I suggest that you type "format long" to see more of the digits that MATLAB is carrying along in the calculation. I expect you will see differences in the less-significant digits.
Such comparisons between floating-point numbers can be tricky. Perhaps you could do some rounding before using the unique() function.
Also, unique() sorts the result, which is why the ordering is "wrong" from your point of view. However, the unique() function also outputs indices that allow you to see exactly how the array was sorted. "doc unique" for details.
  1 Comment
Peter Perkins
Peter Perkins on 1 Dec 2015
"[C,IA,IC] = unique(A,'stable') returns the values of C in the same order that they appear in A, while [C,IA,IC] = unique(A,'sorted') returns the values of C in sorted order."

Sign in to comment.


Stephen23
Stephen23 on 1 Dec 2015

Steven Lord
Steven Lord on 1 Dec 2015
Since this question was originally asked, in release R2015a, we introduced the UNIQUETOL function. You can call UNIQUETOL with a small tolerance to consolidate elements or rows that are "almost" the same when generating a list of unique elements or rows.

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!