Help with Syntax error
Show older comments
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 Comment
Brendan Clark
on 5 Apr 2021
Accepted Answer
More Answers (1)
Image Analyst
on 4 Apr 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);
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!