MATLAB: How to concatenate the changing output from a while loop

plottingwhile loop

I have wrote a code for my home mortgage calculations. The code pretty much runs a simulation on how sooner I would get down with my outstanding principal balance given an additional amount paid each month? I have used a while loop until my principal balance is greater than 0. My counter is the months. So I would like to know how I can plot the counter (months) and the outstanding balance each iteration?
Here is the code:
function out1 = mortgage(outstanding,interestrate,additional)
p = outstanding;
i = interestrate./100;
escrow = 2339.10./12;
payment = 1268.85;
out1=[];
counter=1;
counter1=1;
while p>0
interest = (p.*i)./12;
principal = payment-interest-escrow;
tp = principal+interest+escrow;
if counter1==12
p=p-tp-additional-31.25-1268.85;
counter1=1;
counter=counter+1;
else
p = p-tp-additional-31.25;
counter = counter+1;
counter1=counter1+1;
end
out1=counter;
end

Best Answer

Yogesh - since the outstanding balance is p, then this is the value that you want to save on each iteration of the while loop. Outside of your loop, initialize a variable as
outstandingBalance = p;
Then in the last line of your loop just do
...
outstandingBalance = p;
while p>0
...
out1=counter;
outstandingBalance = [outstandingBalance p]; % update the array of balances
end
Try the above and see what happens!
Related Question