MATLAB: School work question, Having troubles adding onto a matrix

matrixschool

This is my problem:
%Imagine that you are a proud new parent. You decide to start a college saving plan for your child hoping to have enough money in 18 years to pay for cost of education. Suppose that your folks give you a 1000 dollars to start with and you have a 6% interest per year of 0.5% interest per month. Because of interest payments and your contributions, each month you balance will increase in accordance with the formula:
% New balance = old balance + interest + your contribution
% Write a for loop formula to find the saving account balance in 18 years. Plot the values on a time line with horizontal being time and dollar on the vertical
I'm having a problem getting the matrix a(old_balance) to add on each new value. Any advice for fixing this bug. Please and Thankyou.
old_balance = 1000;
interest = .005;
a = zeros(217);
for time = 0:1/12:18
old_balance = old_balance + 100 + (old_balance * interest);
a(old_balance) = old_balance
end

Best Answer

Without having time to read through your full homework question (try to ask specific questions rather than post your entire homework question) there are a few obvious things wrong:
First:
a = zeros(217)
will produce a 2d 217*217 matrix. I assume you want:
a = zeros(1,217)
instead.
Second:
Why are you using a for loop parameterised in that way when you don't use that 'time' loop variable at all?
Finally:
What are you trying to achieve with the line:
a(old_balance) = old_balance;
? You are trying to index into an array starting at index 1000 which is odd to start with, but then subsequent times round the loop the old_balance variable will no longer be integer-valued so cannot be used as an index. But you almost certainly do not want to be using it as an index anyway.
I assume you want something more like:
for n = 1:217
old_balance = old_balance + 100 + (old_balance * interest);
a(n) = old_balance;
end
Almost certainly this isn't the most efficient way to do it, but get the right answer first, then look to efficiency if you need to.
Related Question