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

1 view (last 30 days)
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.

Accepted Answer

Amit
Amit on 7 Feb 2014
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 Comments
Amit
Amit on 7 Feb 2014
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. on 7 Feb 2014
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?

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!