possible bug in "unique" function

5 次查看(过去 30 天)
jenka
jenka 2011-9-29
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

回答(4 个)

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

the cyclist
the cyclist 2011-9-29
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 个评论
Peter Perkins
Peter Perkins 2015-12-1
"[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."

请先登录,再进行评论。


Stephen23
Stephen23 2015-12-1

Steven Lord
Steven Lord 2015-12-1
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.

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by