Problem 3. (25 points total). In Matlab Create a function file called fibonacci.
ID: 3893824 • Letter: P
Question
Problem 3. (25 points total). In Matlab
Create a function file called fibonacci.m that when sent an integer (n) it returns a vector (fib). The vector “fib” contains the first “n” elements of the fibonnacci sequence. Note that the first two numbers of the Fibonacci sequence are 1 and 1, but then every number after is just the sum of the previous two numbers. So 1+1 =2 and then 1+2 =3 and 2+3 =5 and 5+3=8 and so forth. So a Fibonacci sequence looks like: fib= [1 1 2 3 5 8 13 21 34 55 89….] In the command window (see below), call your function file in a single command that creates a vector “f” which is the first 30 elements of the Fibonacci sequence
Explanation / Answer
Save the following code in fibonacci.m
function fib = fibonacci(n)
fib = zeros(1, n);
if(n>1)
fib(1) = 1;
if(n > 2)
fib(2) = 1;
end
end
for i = 3:n
fib(i) = fib(i-1) + fib(i-2);
end
end
------------
Now in command window, you can call the function as fibonacci(30)
Please do rate the answer if helpful. thank you
output
> fibonacci(30)
ans =
Columns 1 through 8:
1 1 2 3 5 8 13 21
Columns 9 through 16:
34 55 89 144 233 377 610 987
Columns 17 through 24:
1597 2584 4181 6765 10946 17711 28657 46368
Columns 25 through 30:
75025 121393 196418 317811 514229 832040
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.