Count unique values in a double

조회 수: 5 (최근 30일)
Emma Kuttler
Emma Kuttler 2022년 3월 1일
답변: Peter Perkins 2022년 3월 2일
I have a single column double with a lot of repeated values. I need to find the number of unique elements of that list (don't care about where they are) and also produce a list of all of the unique values.
When I've tried using unique() and diff() i get these errors.
>> count = unique(x(:,1))
Subscripting into a table using one subscript (as in t(i)) or three or more subscripts (as in t(i,j,k)) is not
supported. Always specify a row subscript and a variable subscript, as in t(rows,vars).
>> b = x([diff(x)~=0, false])
Error using horzcat
Dimensions of arrays being concatenated are not consistent.

답변 (3개)

Walter Roberson
Walter Roberson 2022년 3월 1일
The first error suggests that you might happen to have a table() object named unique in your workspace.
The second error tells you that x has at least three rows, so diff(x)~=0 has at least two rows; you cannot horzcat() a single false onto multiple rows.
By the way, when using logical indexing, you can omit all trailing false in the dimension. For example,
x = 1:5
x = 1×5
1 2 3 4 5
x([true false true false false]) %complete logical indexing
ans = 1×2
1 3
x([true false true]) %trailing false not needed
ans = 1×2
1 3

Fangjun Jiang
Fangjun Jiang 2022년 3월 1일
count = numel(unique(x(:,1)))

Peter Perkins
Peter Perkins 2022년 3월 2일
In addition to what Walter said, if you want the unique values of one variable in a table, likely this is what you should use:
count = unique(x.SomeVarName)
This
count = unique(x(:,1))
will return a shorter one-variable table. That's probably not what you want.

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by