Help with Syntax error
4 views (last 30 days)
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 ');
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)
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.
Walter Roberson on 4 Apr 2021
Edited: Walter Roberson on 5 Apr 2021
That is not a syntax error, that is a semantic error -- you are using the constructs slightly wrong.
You assign to f(1) and f(2). Suppose the user entered 5. Then you say
which is true because the user entered 5
which would be f(5) = f(4)+f(3) .
But f(3) and f(4) do not exist -- only f(1) and f(2) exist.
Furthermore, suppose the user had entered 3, so that f(2)+f(1) had been referenced so f(3) was created. The loop body would succeed, and the loop would start again, and test n > 2. n > 2 is still true because you did not change n, so f(3) would be assigned to again. And then you would loop again...
In any while loop body, you should either be changing at least one value being tested in the while test, or else you should be changing something else and you should have a break statement to exit the loop. For example,
x = floor(x/2);
if abs(x) <= 1; break; end
In your case, since you start with f(1) and f(2) you need something that counts up to n.
Also, watch out: your fprintf() asks to output all of f, not just the last value of f.
And be careful if the user asks for n = 1 or n = 2 that you give the right answer.
What does the homework say you should do if the user enters something that is not a positive integer scalar?
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)
fprintf('Done running %s.m.\n', mfilename);