# Matlab FOR Loop help!

1 view (last 30 days)
Dylan Flores on 29 Jul 2014
Edited: Ben11 on 30 Jul 2014
_ I'm trying to get this function to work. But i keep getting an error. I am trying to determine the amount in the savings account for next 18 years, which is represented by x(k) in an array. Problem is that only the first value for the first month shows up in the array._ * _ * _
clc,clear
% Variable declaration
% x will be used to store the value of the new balance
% a will be used to store the value of the old balance
% i will be used to store the value of the interest rate
% c will be used to store the value of the user's contribution
% Variable initialization
a = input('Enter a value for the initial balance: ');
i = input('Enter a value for the interest rate: ');
c = input('Enter a value that you will contribute: ');
% Calculation
month = 1:12:216;
x=zeros(length(month));
for k=1:length(month);
x(k) = a + i(k) + c
end
Dylan Flores on 29 Jul 2014
Thanks! It works a lot better now!

Ben11 on 29 Jul 2014
Edited: Ben11 on 30 Jul 2014
Maybe try this:
month = 1:12:216;
x=zeros(1,length(month)); % otherwise you have a 18*18 array
x(1) = a;
for k=2:length(month);
x(k) = x(k-1) + (i/100)*x(k-1) + c; % add the amount present during the previous month. Oh and I divided your interest rate by 100.
end
##### 2 CommentsShowHide 1 older comment
Ben11 on 30 Jul 2014
Edited: Ben11 on 30 Jul 2014
You're welcome! It looks like Sara and I arrived at pretty much a similar solution; although I incorrectly used a instead of x(k-1) :)