필터 지우기
필터 지우기

How to count unique value in array?

조회 수: 270 (최근 30일)
tedy
tedy 2013년 4월 6일
댓글: Walter Roberson 2023년 10월 1일
Hello, i have an example array a= [2,2,2,1,1,3,2,1,3,3,2] i do this code
a= [2,2,2,1,1,3,2,1,3,3,2]
unique(a)
histc(a, unique(a))
but, it only result 1,2,3 and 3,5,3 as its frequency.
How to take all the value, but no one duplicate each others. it's like 2,1,3,2,1,3,2 and also with its frequency 3,2,1,1,1,2,1. Thanks in advance

답변 (3개)

balaji
balaji 2019년 6월 12일
편집: balaji 2019년 6월 12일
[cnt_unique, unique_a] = hist(a,unique(a))
  댓글 수: 4
Walter Roberson
Walter Roberson 2023년 10월 1일
@s fry is right: if the array happens to contain only a single value, then unique() would contain only a single value, and hist() would be likely to interpret that value as a bin count instead of as a degenerate list of edges.
Walter Roberson
Walter Roberson 2023년 10월 1일
If you use the newer histogram then you can specify 'BinEdges' as a name/value option instead of passing positionally and having it guess about your intent.

댓글을 달려면 로그인하십시오.


Cedric
Cedric 2013년 4월 6일
편집: Cedric 2013년 4월 6일
You could build something around the following example:
>> b = a([diff(a)~=0, false])
b =
2 1 3 2 1 3
let me know if you need help to get counts. Hint: try using DIFF as well as FIND.
  댓글 수: 2
tedy
tedy 2013년 4월 6일
Thank you cedric. How about the frequency? i code with histc(b, unique(b)), but it result 2,3,2, not 3,2,1,1,1,2,1
Cedric
Cedric 2013년 4월 6일
편집: Cedric 2013년 4월 6일
Look at the following:
>> diff(a)
ans =
0 0 -1 0 2 -1 -1 2 0 -1
as you can see, places where diff is not null are places where there is a transition in the value. These locations can be found using FIND:
>> find(diff(a))
ans =
3 5 6 7 8 10
Now you can probably imagine a solution based on DIFF again..
>> c = diff([0, find(diff(a)), numel(a)])
c =
3 2 1 1 1 2 1
EDIT: I see that Roger posted a solution while I was writing my comment. His solution for getting counts is based on the same principle, but it is better than mine in the sense that it involves only two additional logicals, whereas mine involves a call the NUMEL.

댓글을 달려면 로그인하십시오.


Roger Stafford
Roger Stafford 2013년 4월 6일
f = diff(find([true,diff(a)~=0,true]));
  댓글 수: 1
tedy
tedy 2013년 4월 6일
Thank you so much Roger!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by