How to find the mean of a histogram without the mean function?
조회 수: 23 (최근 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?
댓글 수: 0
채택된 답변
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
trueSD = std(data(:)) % ~0.29
% Take the histogram
h = histogram(data, 10)
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
% 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)
I think there is an error with the variance computation but I'll let you find it.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Histograms에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!