Dividing a range into bins in matlab

patrick.belon picture patrick.belon · Oct 27, 2011 · Viewed 30.7k times · Source

I have the following range from a much larger matrix :

range(a)

ans =

94   153   144    59    79    90   131    64

My professor is asking us to: Divide the range into N = 10 equal-length segments (hereafter called “bins”), and for each bin, find its bounds (aj, bj) as well as its center cj.

(5) Place each measured bacterial count xi into that bin whose lower bound is less than or equal to xi and whose upper bound is greater than xi; thereafter, for each bin count the number of xi assigned to it (= nj).

(6) Plot a histogram of the measured bacterial counts using N = 10 bars. Try the MATLAB functions hist(x,N) and bar(c, n)

I know this is a lot, but I have absolutely no instruction from this guy and would really appreciate a helping hand :)

Answer

Amro picture Amro · Oct 27, 2011

Consider the following example, it should solve all your points:

%# random data vector of integers
M = randi([50 200], [100 1]);

%# compute bins
nbins = 10;
binEdges = linspace(min(M),max(M),nbins+1);
aj = binEdges(1:end-1);     %# bins lower edge
bj = binEdges(2:end);       %# bins upper edge
cj = ( aj + bj ) ./ 2;      %# bins center

%# assign values to bins
[~,binIdx] = histc(M, [binEdges(1:end-1) Inf]);

%# count number of values in each bin
nj = accumarray(binIdx, 1, [nbins 1], @sum);

%# plot histogram
bar(cj,nj,'hist')
set(gca, 'XTick',binEdges, 'XLim',[binEdges(1) binEdges(end)])
xlabel('Bins'), ylabel('Counts'), title('histogram of measured bacterial')

Note that this correctly handles the last bin (read this related question for a discussion on those edge cases)

screenshot