fibonnaci function usingn recursion in matlab

Here's an example of a Fibonacci function using recursion in MATLAB:

main.m
function f = fibonacci(n)
% Computes the nth Fibonacci number using recursion.

if n == 0
    f = 0;
elseif n == 1
    f = 1;
else
    f = fibonacci(n-1) + fibonacci(n-2);
end
176 chars
11 lines

This function defines a recursive function fibonacci that takes an input parameter n, representing the desired Fibonacci number. If n is 0 or 1, the function returns the corresponding Fibonacci number directly. Otherwise, it recursively calls itself to compute the (n-1)th and (n-2)th Fibonacci numbers, and adds their values together to get the nth Fibonacci number.

To use this function, simply call it with the desired value of n, like so:

main.m
>> fibonacci(6)
ans =
     8
29 chars
4 lines

This will compute and return the 6th Fibonacci number, which is 8.

related categories

gistlibby LogSnag