The Fibonacci sequence is a sequence of numbers in which aft
The Fibonacci sequence is a sequence of numbers in which, after the first two numbers, each number is a sum of the proceeding numbers The Fibonacci Sequence starts with 0 and then 1. For subsequent numbers, the sequence follows the following formula: Fibonacci(n) = Fibonacci(n - 1) + Fibonacci(n - 2) Where n is the current position in the sequence The first 10 numbers in the sequence are 0 1 1 2 3 5 8 13 21 34 Write a function that takes an integer number \"n\" as an input and returns a Fibonacci sequence of length n.
Solution
% defining function and returning fib
function fib = fibonacci(N)
fib=zeros(1,N);
fib(1)=0; % first number
fib(2)=1; % second number
k=3;
while k <= N
fib(k)=fib(k-2)+fib(k-1); % adding last two numbers to generate fibonacci series
k=k+1;
end
fprintf(\'%g \',fib);
end
% taking user input
N=input(\'Enter a number : \');
% calling function
fibonacci(N);
---------------------------------------------------------------------
SAMPLE OUTPUT
Enter a number : 20
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
