What did I do wrong in my 'for' loop function?

조회 수: 8 (최근 30일)
Minhao Wang
Minhao Wang 2020년 10월 13일
댓글: Image Analyst 2020년 10월 13일
The question is
With the help of an RESP (Registered Education Savings Plan), a parent can start putting aside money for a child's post-secondary education. Suppose that a young couple deposits $2,000 to start the savings plan, and each month thereafter they contribute $200. Assume that a fixed interested rate of 6.25% per year compounded monthly is applied.
Each month the balance increases according to the following formula: New balance = Old balance + (Old balance * Monthly interest rate) + Monthly contribution
nb(1) = 2000; %the initial balance
mir = 0.0625/12; %monthly rate
mc = 200;% contribution for each month
for B = 2 : 216
nb(B) = (nb(B-1)+1) + ((nb(B-1)+1) * mir) + mc;
end
fprintf('At the end of 18 years you will have saved $ %.2f \n',nb(B))
when you run this, you will get 85431.77, But the correct answer should be 85035.09.
Where did I do wrong?

답변 (2개)

Steven Lord
Steven Lord 2020년 10월 13일
In this line of your code:
nb(B) = (nb(B-1)+1) + ((nb(B-1)+1) * mir) + mc;
What's the old balance? Are you certain that you're accurately carrying over the balance from the previous month into the calculations for the next month? [From the fact that I'm asking these questions, you're probably guessing the answer to that second question is no.]
  댓글 수: 2
Minhao Wang
Minhao Wang 2020년 10월 13일
the old balance(the initial balance) is 2000$ , I don't know where did I do wrong...
Steven Lord
Steven Lord 2020년 10월 13일
If your initial balance nb(1) is 2000, when you go to compute the balance for month 2 nb(2) you start with an old balance of 2001. That may not seem like a big difference, but it's big enough compounded over two years to make your answer incorrect by about $400.

댓글을 달려면 로그인하십시오.


Image Analyst
Image Analyst 2020년 10월 13일
Why are you adding 1 to the old balance nb(B-1)???
  댓글 수: 2
Minhao Wang
Minhao Wang 2020년 10월 13일
I thought that means add a month?
Image Analyst
Image Analyst 2020년 10월 13일
No. B is the month, and the for loop takes care of incrementing the month number. You were improperly adding $1 to the old balance so that's why your answer was more than the correct answer.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by