使用MATLAB的斐波那契数 [英] Fibonacci numbers using matlab
本文介绍了使用MATLAB的斐波那契数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用matlab编写代码来计算前10个斐波那契数.
I need to write a code using matlab to compute the first 10 Fibonacci numbers.
用于计算斐波纳契数的公式为
The equation for calculating the Fibonacci numbers is
f(n)= f(n-1)+ f(n-2)
知道
f(0)= 1和f(1)= 1
f(n) = f(n-1) + f(n-2)
knowing that
f(0) = 1 and f(1) = 1
我写的简单代码是
f(0) = 1;
f(1) = 1;
for i = 2 : 10
f(i) = f(i-1) + f(i-2);
str = [num2str(f(i))];
disp(str)
end
此代码在第1行中给了我错误消息
This code is giving me error message in line 1:
试图访问f(0);索引必须为正整数或逻辑.
Attempted to access f(0); index must be a positive integer or logical.
另一方面,当我将代码修改为
On the other hand, when i modify the code to
f(1) = 1;
f(2) = 2;
for i = 3 : 10
f(i) = f(i-1) + f(i-2);
str = [num2str(f(i))];
disp(str)
end
这很好.
但是我需要它来启动并显示f(0)中的数字.
But I need it to start and display the numbers from f(0).
您能告诉我我的代码有什么问题吗?
Can you please tell me what is wrong with my code?
推荐答案
您可以使用 Binet的公式:
n = 1:10;
r = sqrt(5);
phi = (1+r)/2;
psi = (1-r)/2;
f = (phi.^n - psi.^n)./r;
这篇关于使用MATLAB的斐波那契数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文