Effacer les filtres
Effacer les filtres

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

23 vues (au cours des 30 derniers jours)
Gurpreet Kaur
Gurpreet Kaur le 4 Fév 2023
Commenté : Gurpreet Kaur le 5 Fév 2023
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?

Réponse acceptée

Image Analyst
Image Analyst le 5 Fév 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 commentaire
Gurpreet Kaur
Gurpreet Kaur le 5 Fév 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)

Connectez-vous pour commenter.

Plus de réponses (0)

Produits


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by