imhist and histogram giving different results
9 views (last 30 days)
Show older comments
I'm trying to obtain a histogram of a 1-D signal (type double in the range 0-1). I've tried using two functions - imhist and histogram (also histcounts, which produces the same results as histogram) - and they gave me different results, even though the number of bins was the same in both cases.
Could someone explain to me, which function is the "proper" one to calculate histogram of a signal? What is the difference between them?
My simplified code is below. Result of imhist is plotted directly with result of histogram in figure 1, and in figure 2 to plot both results I used bar function so that the bins from both results are overlapping.You can see that these results are not the same.
I = rand(1e4,1);
[p,lp] = imhist(I(:),256);
figure(1); clf;
ph = histogram(I(:),256); hold on; bar(lp,p); hold off
figure(2); clf;
bar(ph.Values); hold on; bar(p); hold off
0 Comments
Accepted Answer
dpb
on 7 Sep 2022
For <imhist>, the n bins of the histogram are each half-open intervals computed for a double as you've passed as
(p−1.5)/(n−1) ≤ x <(p−0.5)/(n−1)
<histcounts> sorts X into bins such that 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).
Neither is unquestionably "right" nor "wrong", just "different".
0 Comments
More Answers (1)
Steven Lord
on 7 Sep 2022
I suspect that imhist and histogram are just using different algorithms to select the bin edges in the case where you only specify the number of bins. What do you see if you specify the bin edges for histogram using the bin edges computed by imhist? The second output from imhist contains the bin locations. You can pass these in as the second input for histogram. Or you could compare the second output from imhist with the BinEdges property of the object returned by histogram (or the second output argument from histcounts.)
2 Comments
Bruno Luong
on 8 Sep 2022
Not really IMO, it mainly designed to handle discrete values.
It might be not suitable for continuous value as in your case
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!