How do I display only the last iteration

13 ビュー (過去 30 日間)
Noah Kebschull
Noah Kebschull 2017 年 11 月 26 日
回答済み: ABDALHADI ABU ZEYNEH 2020 年 5 月 22 日
I need to find the sum and average of values in a vector without using the mean or sum function, using a FOR loop statement. Let's say my vector is x =[1:1:20]. So far, I have
theSum = 0;
for k =1:length(x);
theSum = theSum + x(k);
fprintf('The total value of x is %.1f, and the average value of x is %.3f\n\n',...,
theSum, theSum/k);
end
I only want to display the final iteration. I'm guessing I need to use the break command, but I don't know how to or where in my statement.

採用された回答

Stephen23
Stephen23 2017 年 11 月 26 日
Move the fprintf to after the loop:
theSum = 0;
for k = 1:numel(x);
theSum = theSum + x(k);
end
fprintf('The total value of x is %.1f, and the average value of x is %.3f\n\n',...,
theSum, theSum/k);

その他の回答 (1 件)

ABDALHADI ABU ZEYNEH
ABDALHADI ABU ZEYNEH 2020 年 5 月 22 日
x='8453365';
theSum = 0;
for k =1:length(x)
theSum = theSum + x(k);
end
disp([theSum, theSum/length(x)])

カテゴリ

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