How can I use for loop to sum some numbers for a certain time?

2 ビュー (過去 30 日間)
Hwajin Choi
Hwajin Choi 2022 年 2 月 28 日
回答済み: Walter Roberson 2022 年 2 月 28 日
I want to sum a set of numbers (10 numbers in the set) for a certain time (user input)
My code is
time = input('Put numbers HERE. ');
CostTotal = 0;
for n = 1:1:time
Cost = [12 21 45 50 13 11 10 77 89 100];
CostTotal = CostTotal + Cost;
end
What I want is, if I put 4 as input, it calculates 12+21+45+50.
Thank you for your help.

回答 (1 件)

Walter Roberson
Walter Roberson 2022 年 2 月 28 日
time = input('Put numbers HERE. ');
CostTotal = 0;
Cost = [12 21 45 50 13 11 10 77 89 100];
for n = 1:1:time
CostTotal = CostTotal + Cost(n);
end

カテゴリ

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

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by