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

조회 수: 1 (최근 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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by