How to count the occurrence of numbers in certain value range (show 0 if no occurrence)
16 views (last 30 days)
Show older comments
Hello everyone,
I konw that I can use function groupcounts to count the occurrence of values.
However I would like to count the times a value appear within a range of values, and if there is no occurrence, it should show 0.
For example, I want to count number occurence between 0 to 20 in array A, while there is no value 10 in A, the output I hope is the 10th cell as 0, but not skipped as using the function groupcounts.
Example:
P=[1 1 3 4 5 6 6 7 7 8 10];
if I run groupcounts
GB=groupcounts(P');
what I get GB is
2
1
1
1
2
2
1
1
What I hope to get as output is
2
0
1
1
1
2
2
0
1
Does anyone know how to code this?
Thanks a lot in advance!
0 Comments
Accepted Answer
John D'Errico
on 9 Nov 2023
Edited: John D'Errico
on 9 Nov 2023
The simple answer is you want to use the wrong tool. Yes, it looks like you want to use groupcounts. But you don't.
P=[1 1 3 4 5 6 6 7 7 8 10];
Counts = accumarray(P',1)
Easy peasy. Yes, with an extra step, you could have used groupcounts. But why, when one line does what you want?
More Answers (1)
Steven Lord
on 9 Nov 2023
If your data is sorted you could use histcounts. In the case of your sample data, where all the values are integers, I'm going to use the "integers" BinMethod.
P=[1 1 3 4 5 6 6 7 7 8 10];
[counts, edges] = histcounts(P, "BinMethod", "integers")
To identify the bin centers rather than the edges:
centers = edges(1:end-1)+diff(edges)./2
If you have non-integer data you might need to explicitly create the bin edges. You can use the unique function for this, but be careful about the last bin (which includes both edges, not just the left edge.)
0 Comments
See Also
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!