While loop inside for loop fibonacci

1 visualización (últimos 30 días)
Dennis Thol
Dennis Thol el 5 de Abr. de 2021
Comentada: Image Analyst el 5 de Abr. de 2021
So I want function to plot the fibonacci series and i want it to stop when it recheas m.
I'm not sure what the error is, it just doesn't run.
Thanks for helping!
function f = fibbo3(m)
n=100;
f=zeros(1,n);
f(1)=1;
f(2)=1;
for k=3:n
while f(k) <= m
f(k) = f(k-1) + f(k-2);
end
end
end

Respuestas (1)

Image Analyst
Image Analyst el 5 de Abr. de 2021
Don't have the while loop. After you assign f(k), just break if the value is more than m
for k=3:n
f(k) = f(k-1) + f(k-2);
if f(k) >= m
break;
end
end
  2 comentarios
Dennis Thol
Dennis Thol el 5 de Abr. de 2021
It works gret, only one problem with it. When I call my function with 12 for example, it looks like this:
1 1 2 3 5 8 13
I don't want the 13 to appear, any tip on how to make show everything up to and equal to "12"?
Image Analyst
Image Analyst el 5 de Abr. de 2021
When you call it, print out the last one:
f = fibbo3(m);
fprintf('The final Fibonacci number with m=%d is %d.\n', m, f(end));
Or else don't pass back the entire array, just pass back the last element:
function f = fibbo3(m)
% code.... then....
f = f(end); % Extract only the very last element of the vector to pass back.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by