Help with If statement in the Fibonacci sequence

Want to create a function to display the Fibonacci numbers up to 30, if a number larger than 30 is entered I want the error message 'Number too big' to be displayed. This is what I have so far. Not sure where I am going wrong.
%% Calculate the first 30 numbers of the Fibonacci sequence, >30 display error message
function fib=FunctionFib2(n)
fib = zeros (1,n);
fib(1)=1;
fib(2)=1;
for i=3:n
fib (i)=fib (i-1) + fib (i-2);
if (n > 30)
disp('Number too big')
end
end

Antworten (1)

sixwwwwww
sixwwwwww am 13 Okt. 2013
Bearbeitet: sixwwwwww am 13 Okt. 2013

0 Stimmen

Dear Sarah, here is correction in your code:
function fib = FunctionFib2(n)
if n > 30
error('Number is too big')
else
fib = zeros(1,n);
fib(1) = 0;
fib(2) = 1;
for i = 3:n
fib(i) = fib(i - 1) + fib(i - 2);
end
end

2 Kommentare

Jan
Jan am 13 Okt. 2013
There is a typo: Sarah wants to start with [1, 1].
Maybe but original Fibonacci series start from 0. I was not well aware with that so I consulted the following link: http://en.wikipedia.org/wiki/Fibonacci_number. However in order to have series start from 1 then
fib = zeros(1,n); --> fib = ones(1,n);
and directly start the loop

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 13 Okt. 2013

Kommentiert:

am 13 Okt. 2013

Community Treasure Hunt

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

Start Hunting!

Translated by