Counting occurrence of elements in an array
Show older comments
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
Accepted Answer
More Answers (1)
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 Comment
Katherine May
on 4 Oct 2024
This also works for array items that aren't numbers!
Categories
Find more on Matrices and Arrays 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!