MATLAB: Reiteration sequence without Fib function.

recursive relation

I am working on a recursive relation for the Fibonacci sequence without using the fib code in Matlab. My code works, but no matter what I do, I cannot get it to print more than the first three numbers.Any advice is appreciated.
function [x,n] = HW215(~)
x(1)=1;
x(2)=(1+sqrt(5))/2;
for n=3:31
x(n)=x(n-1)+x(n-2);
end

Best Answer

Hi Ann,
Sounds like your function should take the following inputs: the first value of your sequence, the second value of your sequence, and the length of the sequence. The function should also return a vector "x" of iterative pair sums.
Be sure that this code is saved in a file name HW215_Ann.m. Then from the Matlab command window, you can type
x=HW215_Ann(1,2,30);
to call your function (use any inputs you like, i used 1, 2, and 30). The output "x" should then be in your workspace with the sequence you wanted.
Function below:
function x = HW215_Ann(f1,f2,n)
% f1 and f2 are the first two numbers of the sequence
% n is the length of the sequence
% Checking that function inputs are valid
if ~isnumeric(f1)||~isscalar(f1),
error('First input "f1" must be numeric scalar.');
end
if ~isnumeric(f2)||~isscalar(f2),
error('Second input "f3" must be numeric scalar.');
end
if ~isnumeric(n)||~isscalar(n),
error('Third input "n" must be numeric scalar.');
elseif (n~=round(n))||n<3,
error('Third input "n" must be an integer 3 or greater.')
end
% pre-allocate memory for x
x=NaN(n,1);
% start off with f1 and f2
x(1)=f1;
x(2)=f2;
% loop to calculate x values
for iter=3:n
x(iter)=x(iter-1)+x(iter-2);
end
Functions in Matlab must be saved as .m files with the same name as the as the function's name. Also, you won't need to use return statements in Matlab. The objects you want to return should only be stated in the function declaration. Give this link a read-through.