Counting occurrence of elements in an array

조회 수: 36 (최근 30일)
Mustafa Sheikh
Mustafa Sheikh 2015년 3월 25일
댓글: Katherine May 2024년 10월 4일
How would I go about counting the occurrence of elements in an array including elements that may not be in the array.
For example if x = [2 3 2 4 5 6 8 2 9 5], I would like to produce an array that has the frequency of each element from 1 to 10 so it'd be output = [0 3 1 1 2 1 0 1 1 0]
Thanks

채택된 답변

Star Strider
Star Strider 2015년 3월 25일
편집: Star Strider 2015년 3월 25일
Use the hist function:
x = [2 3 2 4 5 6 8 2 9 5];
binc = [1:10];
counts = hist(x,binc);
result = [binc; counts]
produces:
result =
1 2 3 4 5 6 7 8 9 10
0 3 1 1 2 1 0 1 1 0

추가 답변 (1개)

Ryan
Ryan 2015년 3월 25일
편집: Ryan 2015년 3월 25일
This works....
x= [2 3 2 4 5 6 8 2 9 5]
for index=1:length(x)
y(index)= sum(x==index);
end
y
produces
x =
2 3 2 4 5 6 8 2 9 5
y =
0 3 1 1 2 1 0 1 1 0
  댓글 수: 1
Katherine May
Katherine May 2024년 10월 4일
This also works for array items that aren't numbers!

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

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by