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!