from
vectorized fibonacci
by Michael Völker
Given any integer array n, compute an array with the nth fibonacci numbers.
|
| fibonacci(n)
|
% Given a matrix of integers n, compute the nth Fibonacci numbers.
% Example:
%
% fibonacci(magic(3))
% ans =
%
% 21 1 8
% 2 5 13
% 3 34 1
% Fibonacci.m by David Terr, Raytheon, 5-11-04
% vectorized by Michael Völker, 07-Jan-2011
function fibs = fibonacci(n)
% Make sure input is sane
if any( ~isreal(n(:)) )
error('Argument must be real.')
end
if any( n(:) ~= floor(n(:)) )
error('Argument must be integers.')
end
alpha = (1 + sqrt(5))/2; % alpha = 1.618... is the golden ratio
fibs = round( alpha.^n ./ sqrt(5) );
neg = n(:) < 0; % negative input is treated separately
% without this if, MATLAB recurses forever
if any( neg )
fibs( neg ) = (-1).^(n(neg)+1) .* fibonacci( -n(neg) );
end
end
|
|
Contact us