How to count the occurrence of numbers in certain value range (show 0 if no occurrence)

11 views (last 30 days)
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!

Accepted Answer

John D'Errico
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)
Counts = 10×1
2 0 1 1 1 2 2 1 0 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
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")
counts = 1×10
2 0 1 1 1 2 2 1 0 1
edges = 1×11
0.5000 1.5000 2.5000 3.5000 4.5000 5.5000 6.5000 7.5000 8.5000 9.5000 10.5000
To identify the bin centers rather than the edges:
centers = edges(1:end-1)+diff(edges)./2
centers = 1×10
1 2 3 4 5 6 7 8 9 10
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.)

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!