Clear Filters
Clear Filters

histcount does not work as excepted

2 views (last 30 days)
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.

Accepted Answer

Steven Lord
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
c = 1×3
2 2 4
d = 1×4
1 2 3 4
[c2,d2]=histc(b,a) % 4 bins
c2 = 1×4
2 2 2 2
d2 = 1×8
1 1 2 2 3 3 4 4
[c3, d3] = histcounts(b, [a Inf]) % 4 bins
c3 = 1×4
2 2 2 2
d3 = 1×5
1 2 3 4 Inf
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)

Categories

Find more on Line Plots in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!