# For loop for fibonacci series

671 ビュー (過去 30 日間)
Yixiang Guice 2018 年 11 月 18 日
Commented: Aquatris 2018 年 11 月 18 日
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

#### 1 件のコメント

Yixiang Guice 2018 年 11 月 18 日
I can include the equation given for this question if required

サインイン to comment.

### 採用された回答

Aquatris 2018 年 11 月 18 日

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

#### 2 件のコメント

Yixiang Guice 2018 年 11 月 18 日
may i ask why is the i from 3 : n instead of 1 to n?
Aquatris 2018 年 11 月 18 日
Because the first two terms of your fibonacci series are (0) and (1) already.

サインイン to comment.