Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

im trying to make a function to determine the nth number in the fibonacci sequen

ID: 3550898 • Letter: I

Question

im trying to make a function to determine the nth number in the fibonacci sequence. heres what i have:


function fib(n)

    F=zeros(1,n+1);

    F(1)=0;

    F(2)=1;

    if n+1 < 1

        disp('n must be greater than or equal to 0')

    end

    for i=3:n+1

        F(i)=F(i-1)+F(i-2);

    end

F(n+1)

end


i have it to output F(n+1) and it works fine for numbers >= 0, but when i put in -1 it says:


n must be greater than or equal to 0

Attempted to access F(0); index must be a positive integer or logical.


Error in fib (line 11)

F(n+1)


I know why it's saying that. It's because im asking for F(n+1). If i change it to just F it will display n must be greater...but it will also give me a vector for F. I don't want a vector for F, i just want it to say n must be greater....

Explanation / Answer

function fib(n)


F=zeros(1,n+1);


F(1)=0;


F(2)=1;


if (n+1 < 1)


disp('n must be greater than or equal to 0')


return;


end


for i=3:n+1


F(i)=F(i-1)+F(i-2);


end


F(n+1)


end