0

Help with Fibonacci function in octave / matlab. The Fibonacci pattern is 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? 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

Original code found from Create faster Fibonacci function for n > 100 in MATLAB / octave

Rick T
  • 3,349
  • 10
  • 54
  • 119
  • 1
    You explicitly write: `if (n==2) f=2`, but are asking us how to make `f=1` in case `n==2` ?? Is this your code? – Ander Biguri Mar 19 '18 at 11:04
  • @AnderBiguri My original question was dealing with speed and wanted to alter it to follow the correct pattern. https://stackoverflow.com/questions/26829209/create-faster-fibonacci-function-for-n-100-in-matlab-octave – Rick T Mar 19 '18 at 11:08

1 Answers1

0

The function you provided assumes the 3rd item of the 0-starting Fibonacci sequence is 2, and that is wrong. 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
Ander Biguri
  • 35,140
  • 11
  • 74
  • 120