简体   繁体   English

Matlab /八度中的斐波那契函数

[英]Fibonacci function in matlab / octave

Help with Fibonacci function in octave / matlab. 八度/ Matlab中的斐波那契函数帮助。 The Fibonacci pattern is http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibtable.html 斐波那契模式是http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibtable.html

0 : 0
1 : 1
2 : 1
3 : 2
4 : 3
5 : 5

The function I have works but it skips a one how can I fix this so the function correctly follows the list above? 我拥有的功能正常运行,但它跳过了one该如何解决此问题,使功能正确地遵循上面的列表? Below is what my function creates. 以下是我的函数创建的内容。

0 : 0
1 : 1
2 : 2
3 : 3
4 : 5
5 : 8

See function below 见下面的功能

function f = rtfib(n)

  if n<0
    multi=-1; %if neg number store neg in multi variable
    n=abs(n); %if neg make pos
  else
    multi=1;
  end


  if (n == 0)
    f = 0;
  elseif (n==1)
    f=1;
  elseif (n == 2)
    f = 2;
  else
    fOld = 2;
    fOlder = 1;
    for i = 3 : n
      f = fOld + fOlder;
      fOlder = fOld;
      fOld = f;
    end
  end
  f=f*multi; %put sign back

end

Ps: I'm using octave 4.0 which is similar to matlab ps:我使用的是与Matlab相似的octave 4.0

Original code found from Create faster Fibonacci function for n > 100 in MATLAB / octave 在MATLAB / octave中为n> 100创建更快的Fibonacci函数找到原始代码

The function you provided assumes the 3rd item of the 0-starting Fibonacci sequence is 2, and that is wrong. 您提供的函数假定从0开始的斐波那契数列的第3项是2,这是错误的。 Just change that. 只是改变它。

function f = rtfib(n)

  if n<0
    multi=-1; %if neg number store neg in multi variable
    n=abs(n); %if neg make pos
  else
    multi=1;
  end


  if (n == 0)
    f = 0;
  elseif (n==1)
    f=1;
  elseif (n == 2)
    f = 1;    % its 1
  else
    fOld = 1; % 1 again.
    fOlder = 1;
    for i = 3 : n
      f = fOld + fOlder;
      fOlder = fOld;
      fOld = f;
    end
  end
  f=f*multi; %put sign back

end

Now it works: 现在可以正常工作:

for ii=0:15
r(ii+1)=rtfib(ii);
end
disp(r)




     0     1     1     2     3     5     8    13    21    34    55    89   144   233   377   610

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM