What to fix in this code to calculate harmonic mean with for loop?
1 view (last 30 days)
Show older comments
I'm working on a homework assignment to calculate the harmonic mean with a for-loop. I recognize there is a MATLAB function to do this already.
I don't really understand how to use for loops to do a summation. The equation I need to create a loop for is: n/[(1/x1)+(1/x2)+...+(1/xN)] where n is the number of data entries, x.
This is what I have currently, which I tried to adapt unsuccessfully from a code for geometric mean:
data=[92.3 93.2 91.9 93.5 92.7 93.1 93.8 92.4];
n=length(data); % n is the number of entries of x in the harmonic mean.
harmonic_mean=0
for q=1:n
z=data(q)
x=harmonic_mean+(1/z)
harmonic_mean=x
end
This is not returning the same answer as the equation I've been provided. Could someone help me understand why my code isn't doing a repetitive summation and how to alter it to get that?
0 Comments
Accepted Answer
Geoff Hayes
on 15 Feb 2016
Trent - you can consolidate the last two lines of code (of your for loop) to
harmonic_mean = harmonic_mean + 1/z;
which should provide the same answer as your code. However, note that the above isn't the harmonic mean but rather is the denominator for the Harmonic Mean equation so should be renamed to something else, say sumOfInverses
sumOfInverses = 0;
for q=1:n
sumOfInverses = sumOfInverses + (1/data(q));
end
with the Harmonic Mean being
harmonicMean = n/sumOfInverses;
as per your equation.
0 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!