Am I misusing hist/histogram?

Sorry if I get the terminologies wrong here, happy for someone to correct me.
I have an array 1x60000 double named "v", one third of the entries (20000) are 6, one third are 36 and one third are 216, scattered throughout.
I've been advised to use hist (and I've experimented with histogram) to get a 1x216 double, with the number of occurences of each entry will be shown by the value in that index.I have no interest in viewing the plot.
With the above, I'd expect to get an array with all zeros, except for a value of 20000 in positions 6, 36, and 216.
H = hist(v,216);
However, in H I get values of 20000 at position 1, 31, and 216.
I've made other arrays with 3 other values, 20000 of each, distributed both randomly and uniformly, but always the result of a value 20000 at positions 1, 31, and 216.
Can someone explain why, please, and help me get the values in the representative positions? In the future I'm looking to have many values distribulted randomly and will want to have an array showing the number of occurences of each value in the corresponding position of the output array.
Many thanks,

Answers (1)

Steven Lord
Steven Lord on 28 Oct 2019
As the note at the top of the documentation page for the hist function states, hist is not recommended. Use histogram (or if you don't need the plot of the distribution, use histcounts.) If all your values are integers, you may want to specify the 'BinMethod' to be 'integers' when you call histcounts, so each integer has its own bin.
Why didn't hist give you the results you expected? If you have to use hist, call it with two output arguments and look at the bin centers (the second output argument.) They're not "nice" values.

1 Comment

Stephen
Stephen on 28 Oct 2019
Edited: Stephen on 28 Oct 2019
Thanks for the input, I've done some more experimenting and found that the first bin edge starts at 5.5, since there are no entries less than 6. I would like to have bins 1 to 5 show as empty and the 6th show as 20000, not the first show as 20000 as currently happens.
I've tried defining the bin edges in an array but it's not really practical for the bigger picture, not least because the size of the output extends far beyond the highest value in the range.
I need to:
Input an array of integers: v, along with the highest value contained within: m.
Output an array of size m with each index in the output (bin?) displaying the occurences of that value in v
e.g. if
v = [6 6 6 6 8 8 8 8 12 12 12 12]
I would think/want
H = histcounts(v,12);
to output
H =
0 0 0 0 0 4 0 4 0 0 0 4
but it does not. It outputs
H =
4 0 0 0 4 0 0 0 0 0 0 4

This question is closed.

Products

Release

R2019a

Asked:

on 28 Oct 2019

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!