histcount does not work as excepted
4 views (last 30 days)
Show older comments
Dear all,
I want to calculate the position of double (or multiple) values inside a list. I found an answer in this forum, however I have stumbled across a problem with histcount. Is the following behaviour of histcount as excepted. The function histc works perfectly.
a=[1 2 3 4];
b=[1 1 2 2 3 3 4 4];
[c,d]=histcounts(b,a);
multi=sum(b==d(c>=2)')>=1
% 1 1 1 1 1 1 0 0
[c,~]=histc(b,a);
multi=sum(b==a(c>=2)')>=1
% 1 1 1 1 1 1 1 1
The algorithm is based on:
I use Matlab 2018a on a Ubuntu 20.04 LTS system.
0 Comments
Accepted Answer
Steven Lord
on 6 Nov 2021
The value X(i) is in the kth bin if edges(k) ≤ X(i) < edges(k+1). The last bin also includes the right bin edge, so that it contains X(i) if edges(end-1) ≤ X(i) ≤ edges(end).
The first bin counts values in b that satisfy 1 <= b < 1
The last bin counts values in b that satisfy 3 <= b <= 4.
Thus histcounts is behaving as expected.
histc had an extra bin that counted exactly those values that matched the last element of the edges.
a=[1 2 3 4];
b=[1 1 2 2 3 3 4 4];
[c,d]=histcounts(b,a) % 3 bins
[c2,d2]=histc(b,a) % 4 bins
[c3, d3] = histcounts(b, [a Inf]) % 4 bins
In that last histcounts call the next-to-last bin counts elements of b that satisfy 3 <= b < 4 and the last bin those that satisfy 4 <= b <= Inf. I could have used any value greater than or equal to 4 as that last bin edge, but Inf guarantees you catch any non-NaN real values in your data no matter how large they are.
If you're looking to find where certain values are located in a list, perhaps the ismember function would be more suitable for your application?
More Answers (0)
See Also
Categories
Find more on Data Distribution Plots 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!