MATLAB: Future Bank Account Balance

homeworkwhile loop

I have to create a while loop that will calculate how much money will be in my bank account 18 years from now. I start off with $2000, the interest is 0.4%, and my contribution to the account each month is $150. I have to use a while loop to do this and have a plot to show its increase over time. This is what I have but can't seem to make it work:
oldbalance = 2000;
contribution = 150;
while i <= 216
interest = 0.4/100*oldbalance;
newbalance(i) = oldbalance(i) + interest(i) + contribution(i);
oldbalance = newbalance(i);
ylabel('amount in the account in dollars');
title('Plot of amount in the account as a function of time');

Best Answer

  • This line overwrites your old balance vector with a scalar
    oldbalance = newbalance(i);
    Instead of keeping track of old balance and new balance separately, just have a single variable to keep track of the balance. E.g.,
    balance = 2000;
    contribution = 150;
    i = 1; % you need to initialize i
    while i < 216
    interest = 0.4/100*balance(i);
    balance(i+1) = balance(i) + interest + contribution; % assumes contribution goes in at the end of the period.
    i = i + 1; % you need to increment i
    Also, you might want to double check to see if that interest rate is annual or monthly. If it is annual and you are compounding it monthly, then you would need to divide that rate by 12.
    Seems like this problem is more suited to a for-loop than a while-loop.