How to fix: Index exceeds matrix dimensions

1 vue (au cours des 30 derniers jours)
Chun Yong Koh
Chun Yong Koh le 23 Août 2019
Commenté : Chun Yong Koh le 24 Août 2019
Hi,
I am new to matlab and am trying to write a function which produces the Fibonacci sequence of input n. I am required to write it in a way so that the program returns all Fibonacci numbers which are less than 3000, including the index of the highest term below 3000. However, I kept getting the error ( Index exceeds matrix dimensions ) at where the if loops is located. May i know how I can change it to make it work?
function y=fibonacci(n)
y(1)=1;
y(2)=1;
for i=3:n
y(i) = y(i-1)+y(i-2);
i=i+1; %#ok<*FXSET>
if y(i) > 3000
disp(i-1);
break
end
end

Réponses (1)

Torsten
Torsten le 23 Août 2019
The for-loop increases i automatically. Thus remove the line "i=i+1".
  1 commentaire
Chun Yong Koh
Chun Yong Koh le 24 Août 2019
Really new to this but thanks for the help!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by