斐波那契序列无需在八度中循环

发布于 2025-01-17 18:29:16 字数 236 浏览 1 评论 0原文

我正在尝试创建一个没有八度 for 循环的斐波那契序列,但我得到的只是错误,我完全被困在这里。关于如何处理这个问题的任何想法

x(1)=1;
x(2)=1;
m=3:10
x(m)=x(m-1)+x(m-2)

错误:x(9):超出范围 2(尺寸为 1x2)

我期待获得第一个 10 斐波那契数列,但它不起作用

I'm trying to create a Fibonacci sequence without for loop in octave, but all I get is error and I'm totally stuck here. Any ideas on how to deal with this

x(1)=1;
x(2)=1;
m=3:10
x(m)=x(m-1)+x(m-2)

error: x(9): out of bound 2 (dimensions are 1x2)

I was expecting getting the 1st 10 Fibonacci sequence but it isn't working

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

携君以终年 2025-01-24 18:29:16

不幸的是,八度不会在每个步骤(据我所知)重新计算就位的矢量化运算符(也不是MATLAB),因此

octave> x=ones(1,10)
x =
   1   1   1   1   1   1   1   1   1   1

octave> x(3:10)=x(2:9)+x(1:8)
x =
    1   1   2   2   2   2   2   2   2   2

您可以使用评论中提到的封闭形式的表达式,或者只是做一个简单的表达式环形:

octave> x=ones(1,2)
octave> for i=3:10
> x(i)=x(i-1)+x(i-2)
> endfor

Unfortunately, Octave does not recalculate in-place vectorized operators at each step (nor MATLAB, as far as I'm aware of), so

octave> x=ones(1,10)
x =
   1   1   1   1   1   1   1   1   1   1

octave> x(3:10)=x(2:9)+x(1:8)
x =
    1   1   2   2   2   2   2   2   2   2

You can either use a closed-form expression, as mentioned on the comments, or just do a simple loop:

octave> x=ones(1,2)
octave> for i=3:10
> x(i)=x(i-1)+x(i-2)
> endfor
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文