MATLAB Answers

0

For loop for fibonacci series

Yixiang Guice さんによって質問されました 2018 年 11 月 18 日
最新アクティビティ 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.

タグ

1 件の回答

Aquatris
回答者: Aquatris
2018 年 11 月 18 日
編集済み: 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.



Translated by