Compound yearly interest with loop
80 views (last 30 days)
I'm trying to compute compound interest with loops. I'm currently using a while loop, but I don't know if that's the easiest solution. Right now, the code is producing the first year, but I can't get it to repeat more than that.
Here's the problem: Imagine that you went to the bank and deposited $15,000 in an account that earns 7% interest every year, with each year’s interest being deposited back into the account. Write a MATLAB program that computes the number of years it would take to accumulate $400,000.
This is the code I have so far
%compute the interest of amount in bank
%initilize variable called 'prod' to 15000
Image Analyst on 18 Nov 2016
Edited: Image Analyst on 15 May 2020
% Compute the interest of amount in bank
fontSize = 20
principal = 15000
final(1) = principal;
loopCounter = 1;
while final(end) < 40000
loopCounter = loopCounter + 1;
final(loopCounter) = final(loopCounter - 1) * (1 + interest);
numYears = loopCounter - 1;
fprintf('At the end of year #%d, the balance is $%.2f\n', numYears, final(loopCounter));
plot(1:loopCounter, final, 'bo-', 'LineWidth', 2);
title('Compounded Interest', 'FontSize', fontSize);
xlabel('Year', 'FontSize', fontSize);
ylabel('Balance', 'FontSize', fontSize);
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
% Get rid of tool bar and pulldown menus that are along top of figure.
set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')