Help with Syntax error
Mostrar comentarios más antiguos
Hey, to preface this post, I'm very new to this and I'm still trying to learn the basics.
I'm trying to get this particular code to take input n and output the corresponding fibonnaci number. ie; input 5 should output 8.
The script window doesn't show any error messages, however, when I run it, an error pops up. I haven't run into this issue before.
The code is:
f(1) = 1;
f(2) = 2;
n = input('Enter number of term desired ');
while n>2
f(n)= f(n-1)+f(n-2);
end
fprintf('the %dth fibonacci number is %d',n,f)
The error is
Index exceeds the number of array elements (2).
Error in Untitled (line 5)
f(n)= f(n-1)+f(n-2)
I assume that I'm somehow creating an array n when I want to say that while variable n is above a certain number, this is true.
I do need to use a while loop to accomplish this. Yes this is homework.
1 comentario
Brendan Clark
el 5 de Abr. de 2021
Respuesta aceptada
Más respuestas (1)
Image Analyst
el 4 de Abr. de 2021
Your while loop will get into an infinite loop because your n never changes. while loops always need to have a failsafe which is a limit on the number of iterations, and yours does not have that so it will go on forever. Anyway, you only compute a certain term but the terms in Fibonacci series depend on the prior term, so you're going to have to have a for loop with iterator k and go up to n and then it should work
fprintf('Beginning to run %s.m ...\n', mfilename);
n = input('Enter desired number of terms : ');
f(1) = 1;
f(2) = 2;
for k = 3 : n
% Compute F(k)
f(k) = f(k - 1) + f(k - 2)
end
f
fprintf('Done running %s.m.\n', mfilename);
Categorías
Más información sobre Startup and Shutdown en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!