Using Matlab perform the following: The geometric mean of a set of numbers x 1 t
ID: 643901 • Letter: U
Question
Using Matlab perform the following:
The geometric mean of a set of numbers x1 through xn is defined as the nth root of the product of numbers:
Geometric mean = (x1*x2xn)1/n
Write a function file that will accept an arbitrary number of positive input values and calculate the average and the geometric mean of the numbers. Use a while loop to get the input values and terminate the input if the user inputs a negative number. Test your program by calculating the average and geometric mean of the four numbers 2,3,4 and 5.
Explanation / Answer
main.m
prompt='Enter postive number and negetive number to terminate:';
x=0;
i=1;
while(x>=0)
x=input(prompt);
if x>=0
a(i)=x;
i=i+1;
end
end
disp('Average:');
disp(Average(a(:)));
disp('Geometric Mean:');
disp(GeometricMean(a(:)));
Average.m
function avg = Average( a )
avg=0;
for i=1:length(a)
avg=avg+a(i);
end
avg=avg/length(a);
end
GeometricMean.m
function gm = GeometricMean( a )
gm=1;
for i=1:length(a)
gm=gm*a(i);
end
gm=gm^(1/length(a));
end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.