sum values of histogram bins

41 views (last 30 days)
john Chandler
john Chandler on 28 May 2014
Edited: Image Analyst on 28 May 2014
Hi, I have data on particle intensities. I am binning the particles into bins based upon the intensities. This code is working.
histBins=[10, 25, 50, 75, 100, 150, 200];
a=hist(d,histBins);
I will now like to sum up the intensity of all the particles in each bin. Is there a way to do this?
Thanks, John

Accepted Answer

Sean de Wolski
Sean de Wolski on 28 May 2014
Building on The Cyclist's answer, use accumarray to do the summing:
x = randn(100,1);
edges = -10:10;
[~, idx] = histc(x,edges);
binsums = accumarray(idx,x)

More Answers (2)

Image Analyst
Image Analyst on 28 May 2014
Edited: Image Analyst on 28 May 2014
No need to mess with histograms, and resulting loss of precision. If you want "sum up the intensity of all the particles", just sum the particles themselves, not the histogram bins.
sumOfAllParticleIntensities = sum(d);
If you want the sums of all particle intensities bin by bin between the bin edges that you gave, then you can do this:
histBins=[10, 25, 50, 75, 100, 150, 200];
x = 200*randn(100,1);
for k = 1 : length(histBins)-1
indexes = x > histBins(k) & x <= histBins(k+1);
binByBinSums(k) = sum(x(indexes));
end
% Print to command window:
binByBinSums
This will be more accurate than doing anything based on counts and the values of the bin centers.

the cyclist
the cyclist on 28 May 2014
Edited: the cyclist on 28 May 2014
If you change your code to use the histc() command instead of the hist() command, then you can do
[count,idx] = histc()
will give you the index to which bin each element was sorted into. You can use that index sum the intensities in each bin.
[histc() specifies the bins based on edges, rather than centers.]

Community Treasure Hunt

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

Start Hunting!