patrick.belon
patrick.belon

Reputation: 65

Dividing a range into bins in matlab

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 :)

Upvotes: 2

Views: 31037

Answers (2)

Amro
Amro

Reputation: 124563

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

Upvotes: 8

Tal Darom
Tal Darom

Reputation: 1409

computing histogram:

range = [94   153   144    59    79    90   131    64]
[n,xout] = hist(range, 10)

xout is bin centers, n bin counts.

plotting bar graph:

 bar(xout,n)

computing bin edges:

width = xout(2)-xout(1)
xoutmin = xout-width/2
xoutmax = xout+width/2

Upvotes: 3

Related Questions