フィルターのクリア

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

23 ビュー (過去 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 件)

カテゴリ

Help Center および File ExchangeHistograms についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by