I am having some difficulty trying to fill a table with the number of elements in each bin while also making a table that holds the elements in each bin.
Okay, let me go over my thoughts:
So I have a list:
dat = {0,1,3,9,11,13,14,15,19,20};
I want to have each bin be a constant width, which I have set at 5, so I know to find the number of bins:
numBins = (Max[dat] - Min[dat])/width
To get my intervals, I wrote:
intervals = Table[0,2*numBins];
intervals[[1]] = min;
For[i = 2, i < 2*numBins, i+=2, intervals[[i]] = intervals[[i-1]] + width; intervals[[i+1]] = intervals[[i]]]
intervals[[2*numBins]] = intervals[[2*numBins - 1]] + width;
which gets me:
{0, 5, 5, 10, 10, 15, 15, 20}
which is exactly what I'm looking for. Now, I know that for the bins, I should get:
0-5, 5-10, 10-15, 15-20 (intervals)
0 9 11 19 (elements in bins)
1 13 20
3 14
15
3 1 4 2 (number of elements in each bin)
Now, I thought that to get the number of elements in each bin and fill in a bin table, I might do something like (pseudocode-ish)
int k = 0;
numOfElements = Table[0, {i,numBins}]
elements = Table[0, {i, numBins}, {j, Length[dat]}]
for(int i = 2, i < Length[intervals], i+=2){
for(int j = 0, j < Length[dat], j++){
if(dat[[j]] > intervals[[i]] && dat[[j]] < intervals[[i+1]]){
elements[[i]][[j]] = dat[[j]];
count++;
}
numOfElements[[k]] = count;
k++;
count = 0;
}}
What I'm having problems with is 1) is this the correct logic? and 2) implementing in Mathematica. Any help in tackling this problem would be greatly appreciated.
EDIT: @kglr pointed out a lot of good stuff and I also noticed BinCounts, which is useful, but I noticed that
BinLists[dat, 5] /. {}->Nothing
gets me
{{0, 1, 3}, {9}, {11, 13, 14}, {15, 19}, {20}}
when what I'm looking to try to get is
{{0, 1, 3}, {9}, {11, 13, 14, 15}, {19, 20}}
So while BinLists gets me something close, it's not quite what I'm trying to do.
BinLists
andHistogramList
? $\endgroup$BinLists
does: Binlists >> Details : _BinLists[data,dx] takes the bin boundaries to be integer multiples of dx, with the first bin starting at Ceiling[Min[data]-dx,dx] and the last bin ending at Floor[Max[data]+dx,dx]. _ $\endgroup$