How to find the mean of a histogram without the mean function?

10 views (last 30 days)
Can anyone give an example code on how to find the average/mean value of an histogram without using the mean or sd function, but rather making using of the bin width?

Accepted Answer

Image Analyst
Image Analyst on 5 Feb 2023
What about a for loop summing up the values then dividing by the number of items you summed?
data = rand(100);
trueMean = mean(data, 'all') % ~0.5
trueMean = 0.4962
trueSD = std(data(:)) % ~0.29
trueSD = 0.2902
% Take the histogram
h = histogram(data, 10)
h =
Histogram with properties: Data: [100×100 double] Values: [1014 1064 996 1029 915 1029 983 961 1010 999] NumBins: 10 BinEdges: [0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000 0.8000 0.9000 1] BinWidth: 0.1000 BinLimits: [0 1] Normalization: 'count' FaceColor: 'auto' EdgeColor: [0 0 0] Show all properties
counts = h.Values;
binCenters = ([h.BinEdges(1:end-1) + h.BinEdges(2:end)])/2;
% for loop to sum data instead of using mean() and std().
theSum = 0;
numBins = numel(binCenters);
for k = 1 : numBins
sumInThisBin = counts(k) * binCenters(k);
theSum = theSum + sumInThisBin;
end
nMinus1 = sum(counts) - 1;
theMean = theSum / nMinus1
theMean = 0.4965
% Compute variance
theSumsSquared = 0;
for k = 1 : numBins
sumInThisBin = counts(k) * (binCenters(k) - theMean);
theSumsSquared = theSumsSquared + sumInThisBin ^ 2;
end
theVariance = theSumsSquared / (sum(counts)-1);
stdDev = sqrt(theVariance)
stdDev = 9.1852
I think there is an error with the variance computation but I'll let you find it.
  1 Comment
Gurpreet Kaur
Gurpreet Kaur on 5 Feb 2023
Thanks! I believe this was the fix to the variance computation.
theSumsSquared = 0;
for k = 1 : numBins
sumInThisBin = counts(k) * (binCenters(k) - theMean)^2;
theSumsSquared = theSumsSquared + sumInThisBin;
end
theVariance = theSumsSquared / (sum(counts)-1);
stdDev = sqrt(theVariance)

Sign in to comment.

More Answers (0)

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!