How to use a loop to find a sum and average?

62 ビュー (過去 30 日間)
Mark Dillon
Mark Dillon 2015 年 7 月 11 日
回答済み: Image Analyst 2015 年 7 月 11 日
I am learning how to use MATLAB and have been told there is a way to create a loop that will also output the sum and the average. What I have done so far is to create an array of a random sort of numbers and printed out each element as shown below:
% Variables
x = [1.8 3.6 5.4 7.2];
fprintf('x =');
disp(x);
% For Loop
for k = 1:length(x);
fprintf('Element %0.0f is: %0.1f \n', k, x(k));
end
What I need to figure out next is how to use the 'for' loop to also print out the sum and average.

採用された回答

Image Analyst
Image Analyst 2015 年 7 月 11 日
Try this:
% Variables
x = [1.8 3.6 5.4 7.2]
% For Loop
theSum = 0; % Initialize
for k = 1 : length(x);
fprintf('Element %d is: %0.1f \n', k, x(k));
% Accumulate the sum
theSum = theSum + x(k);
% Compute the running mean and print out.
fprintf('After element #%d, the sum = %.1f, and the mean = %.3f\n\n',...
k, theSum, theSum/k);
end

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2015 年 7 月 11 日

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by