Geometric Mean and average.

2 ビュー (過去 30 日間)
David Hughes
David Hughes 2015 年 7 月 8 日
回答済み: David Hughes 2015 年 7 月 9 日
I am trying to create a code that will accept inputs until a negative integer is entered then take all the positive integers as a vector and calculate the geometric mean and average. This is what i have so far. I can enter the vector and get an output but I need to have it loop for each element of vector as described above. Any help is appreciated.
%gm is geometric mean. avg is the average
x = input('Enter your numbers: '); n = length(x);
gm = 1; % Initialize variable
for i = 1 : n % Iterate through all of the elements y = x(i); gm = gm * y^(1/n); % Compute mean end avg = sum(x)/n; % Compute average fprintf('The Geometric mean is %.3f \n',gm) fprintf('The average is %.3f \n',avg)

回答 (1 件)

David Hughes
David Hughes 2015 年 7 月 9 日
I think I found the answer.
i=1; n=1; while n >= 0 ix = input('Enter your numbers: '); if ix < 0 % break else x(i)= ix; end i=i+1; end %gm is geometric mean. avg is the average n = length(x); gm = 1; % Initialize variable for i = 1 : n % Iterate through all of the elements y = x(i); gm = gm * y^(1/n); % Compute mean end avg = sum(x)/n; % Compute average fprintf('The Geometric mean is %.3f \n',gm) fprintf('The average is %.3f \n',avg)

カテゴリ

Help Center および File ExchangeNumerical Integration and Differentiation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by