MATLAB: How to divide a column in equal density bins.

equal density binquantile

I have a column of values of which some are missing (nan). I want to implement a function that discretizes them into 10 equal density bins (not equal width). So, each bin will have approximately the same number of samples and that function returns me original index of all values in each bin. Note: Nan must be ignored. I tried quantile but the values in each bin are different. Any help?

Best Answer

sortvals = sort(YourData(~isnan(YourData)));
binwidth = floor(length(sortvals)/10);
leftover = length(sortvals) - binwidth*10;
bincontents = cell2mat(sortvals(:), [binwidth*ones(1,9), leftover], 1);
The extras that do not fit within equal-width bins are allocated arbitrarily to the last bin.