Finding the geometric mean of inputted numbers??

Hello, I have some trouble with my code. The objective of it is to accept an arbitrary number of positive input values and calculate both the arithmetic mean, and the geometric mean of the numbers. For this I have to use a while loop to get my inputs for the number, and to terminate the inputs if the user enters a negative number. Here is what I have so far.
clc
clear
k = 0;
while k >= 0
a = input('Give me the first number');
b = input('Give me the second number');
c = input('Give me the third number');
x = geomean(a,b,c);
y = mean(a,b,c);
if a, b, c, d < 0;
break;
end
end
disp(x)
disp(y)
I keep getting an error that says "too many input arguments" for the geomean function. Can anyone help out?

Answers (2)

Use the square brackets [ ] to concatenate your inputs into a vector. E.g.,
x = geomean([a,b,c]);
y = mean([a,b,c]);
Also, you probably meant something like this for your if-test
if any([a,b,c] < 0)
One approach:
. . .
v = [a b c];
x = geomean(v);
y = mean(v);
. . .

2 Comments

I seemed to have changed something but now I am in an infinite loop where it asks me for the three inputs over and over. What went wrong?
clc
clear
k = 0;
while k <= 0
a = input('Give ne the first number');
b = input('Give me the second number');
c = input('Give me the third number');
v = [a b c];
x = geomean(v);
y = mean(v);
if any([a,b,c]< 0)
break;
end
end
disp(x)
disp(y)
Looking at the code you posted, it seems ‘k’ never changes, so the while condition remains true. Also, the break should break out of the loop, but for some reason doesn’t. I replaced it with a return that does.
This works, and does not create an infinite loop. Experiment with it to get the result you want. (I replaced input with inputdlg because I prefer it. Change it back if that works best for you. It will not affect the rest of your code.)
The (Revised) Code
k = 0;
while k <= 0
a = inputdlg('Give me the first number');
b = inputdlg('Give me the second number');
c = inputdlg('Give me the third number');
v = str2double([a b c]);
if any(v < 0)
return;
end
x = geomean(v);
y = mean(v);
k = k + 1;
end

Sign in to comment.

Asked:

on 19 Oct 2017

Commented:

on 20 Oct 2017

Community Treasure Hunt

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

Start Hunting!