Storing values in a for loop when input vector is not used in calculation

3 ビュー (過去 30 日間)
B.M.
B.M. 2014 年 2 月 7 日
コメント済み: B.M. 2014 年 2 月 7 日
I'm working through examples in "Matlab for Engineers and Scientists" and am having trouble with this problem:
=============================
Suppose you deposit $50 in a bank account every month for a year. Every month, after the deposit has been made, interest at the rate of 1% is added to the balance: After one month the balance is $50.50, and after two months it is $101.51. Write a program to compute and print the balance each month for a year. Arrange the output to look something like this:
MONTH MONTH-END BALANCE
1 50.50
2 101.51
3 153.02
...
12 640.47
=============================
Obviously the vector of months shows up fine, but I can't get the balance vector figured out...if I used the months vector in the calculation of balance I know I'd get a vector, but my current code overwrites the previous balance from last month. I don't use the months vector for anything but a counter/index:
=============================
Monthly=50;
Months=[1:12];
Balance=0;
for k=1:length(Months)
Balance=(Balance+(Monthly))*1.01;
end
disp('MONTH MONTH-END BALANCE')
disp([Months' Balance'])
=============================
I know I can do this using the month as an exponent on the rate but just want to know if there's a way to get a vector of balances by modifying the code above.

採用された回答

Amit
Amit 2014 年 2 月 7 日
Monthly=50;
Months=[1:12];
Balance=0;
disp('MONTH MONTH-END BALANCE')
for k=1:length(Months)
Balance=(Balance+(Monthly))*1.01;
disp([Months(k) Balance])
end
  2 件のコメント
Amit
Amit 2014 年 2 月 7 日
And if you really want to store the values,
Monthly=50;
Months=[1:12];
Balance=zeros(12,1);
Balance(1) = Monthly*1.01;
for k=2:length(Months)
Balance(k)=(Balance(k-1)+(Monthly))*1.01;
end
B.M.
B.M. 2014 年 2 月 7 日
So your first post did the trick. So the problem was that the displayed vectors had to reference the index k, and that statement had to be in the for loop?

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

その他の回答 (0 件)

カテゴリ

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