Help with Syntax error
이전 댓글 표시
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개)
Image Analyst
2021년 4월 4일
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);
카테고리
도움말 센터 및 File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!