How to count the occurrence of numbers in certain value range (show 0 if no occurrence)
8 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
John D'Errico
2023-11-9
编辑:John D'Errico
2023-11-9
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?
更多回答(1 个)
Steven Lord
2023-11-9
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!