MATLAB: For loop for fibonacci series

for loop

i am supposed to write a fibonacci series that calculate up to n term and (n-1) term but i am stuck at calculating the (n-1)term. can anyone help? ( i am new to matlab)
a = 0;
b = 1;
x = n-1;
n = input('Enter number of term desired');
for i = 1:n %term for n
fprintf('\t')
fprintf('%d',a);
c = a + b;
a = b;
b = c;
end
for i = n:x %term for n-1
fprintf('\t')
fprintf('%d',a);
c = a + b;
a = b;
b = c;
end

Best Answer

In case of series, it is better to store each value. Please see below code that generatesa fibonacci sequence, and stores all the values in the variable"a";
a(1) = 0;
a(2) = 1;
n = input('Enter number of term desired ');
for i = 3:n
a(i) = a(i-1)+a(i-2);
end
From here, if you want the n'th term, you do a(n), if you want the n-1, then you do a(n-1).
You method of trying to find the n-1 term can work with the following modification;
a = 0;
b = 1;
n = input('Enter number of term desired');
for i = 1:n-2 %term for n
c = a + b;
a = b;
b = c;
end
a_n = c; % nth term
a_n1 = a; %(n-1) term