output the nth term in the fibonacci sequence in matlab

main.m
function res = fibonacci(n)
  if n==0 || n==1 
    res = n;
  else
    res = fibonacci(n-1) + fibonacci(n-2);
  end
end
120 chars
8 lines

This is a simple recursive implementation of the fibonacci sequence. To output the nth term, you can simply call the function with the desired value of n and store the result in a variable. For example, to output the 8th term:

main.m
n = 8;
fib_n = fibonacci(n);
disp(fib_n);
42 chars
4 lines

The output will be 21, which is the 8th term in the fibonacci sequence.

Alternatively, you can use a loop to calculate the sequence up to the nth term without recursion:

main.m
n = 8;
fib = zeros(1,n+1); % preallocate array
fib(2) = 1;
for i=3:n+1
  fib(i) = fib(i-1) + fib(i-2);
end
fib_n = fib(n+1);
disp(fib_n);
138 chars
9 lines

This will give the same output as the previous example.

gistlibby LogSnag