使用MATLAB的斐波那契数

编程入门 行业动态 更新时间:2024-10-25 18:25:00
本文介绍了使用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的斐波那契数

本文发布于:2023-11-29 01:01:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644659.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:MATLAB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!