How to find the mean of a histogram without the mean function?
23 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Gurpreet Kaur
am 4 Feb. 2023
Kommentiert: Gurpreet Kaur
am 5 Feb. 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?
0 Kommentare
Akzeptierte Antwort
Image Analyst
am 5 Feb. 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
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.
1 Kommentar
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Histograms finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!