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

조회 수: 7 (최근 30일)
Gurpreet Kaur
Gurpreet Kaur 2023년 2월 4일
댓글: Gurpreet Kaur 2023년 2월 5일
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