Finding the nth term of the fibonacci sequence in matlab.

9 visualizaciones (últimos 30 días)
Sara Jones
Sara Jones el 28 de Oct. de 2018
Comentada: Star Strider el 28 de Oct. de 2018
I am attempting to write a program that takes a user's input (n) and outputs the nth term of the Fibonacci sequence, without using any of MATLAB's inbuilt functions. I have currently written the following function, however I wish to alter this code slightly so that n=input("Enter value of n") however I am unsure how to go about this? Do I need to declare an empty array called fib1?
function f = fib1(n)
if n <= 1
f = 1;
else
f = fib1(n-1) + fib1(n-2);
end

Respuestas (1)

Star Strider
Star Strider el 28 de Oct. de 2018
You have the correct approach.
Try this:
n = input("Enter value of n ");
f = fib1(n)
When this is then run, the result is:
Enter value of n 10
f =
89
  2 comentarios
Sara Jones
Sara Jones el 28 de Oct. de 2018
I tried the suggestion you provided and I obtain the following error: Undefined function or variable 'fib1'. The code is as follows:
n=input("Enter value of n");
f = fib1(n);
if n <= 1
f = 1;
else
f = fib1(n-1) + fib1(n-2);
end
Star Strider
Star Strider el 28 de Oct. de 2018
You must save your function in a separate file called ‘fib1.m’.
Then my Answer will work.

Iniciar sesión para comentar.

Categorías

Más información sobre Encryption / Cryptography en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by