How to access the 3rd element in a for loop?

3 ビュー (過去 30 日間)
Steven Gangano
Steven Gangano 2022 年 1 月 31 日
コメント済み: Steven Gangano 2022 年 1 月 31 日
investment = 1000;
interestRate = 0.01;
months =[1:12];
for month = months
investment = investment * (1 + interestRate);
end
Displays:
investment = 1010
investment = 1020.1
investment = 1030.3
investment = 1040.6
investment = 1051.0
investment = 1061.5
investment = 1072.1
investment = 1082.9
investment = 1093.7
investment = 1104.6
investment = 1115.7
investment = 1126.8

採用された回答

Walter Roberson
Walter Roberson 2022 年 1 月 31 日
You would have to evalc() an invocation of the for loop, and do text processing on the output.
We would recommend that you instead record the values as you go.
investment = 1000;
interestRate = 0.01;
months =[1:12];
for month = months
investment(month+1,1) = investment(month,1) * (1 + interestRate);
end
format long g
investment
investment = 13×1
1.0e+00 * 1000 1010 1020.1 1030.301 1040.60401 1051.0100501 1061.520150601 1072.13535210701 1082.85670562808 1093.68527268436
The third output of the loop would then be investment(4) [because investment(1) is the initial value]
  1 件のコメント
Steven Gangano
Steven Gangano 2022 年 1 月 31 日
Thank you! Can you explain the part:
investment(month+1,1)
What does month+1 do?

サインインしてコメントする。

その他の回答 (1 件)

KSSV
KSSV 2022 年 1 月 31 日
investment = zeros(13,1);
investment(1) = 1000;
interestRate = 0.01;
months =[1:12];
for month = months
investment(month+1) = investment(month) * (1 + interestRate);
end
investment(4)
ans = 1.0303e+03

カテゴリ

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