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

8 次查看(过去 30 天)
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?

采纳的回答

Image Analyst
Image Analyst 2023-2-5
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 个评论
Gurpreet Kaur
Gurpreet Kaur 2023-2-5
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)

请先登录,再进行评论。

更多回答(0 个)

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by