The syntax of your functions, and calling your functions is fine in each case. Your functions, on the other hand, have some semantic problems.
In get_fact
:
function [ nfactorial ] = get_fact( n )
%input a non-negative integer
%output is factorial of that integer
for i=0:n
nfactorial=prod(1:n);
end
prod(1:n)
will multiply the numbers from 1
to n
, see help :
and help prod
. So it exactly calculates the factorial by itself! No need to have a loop over i
: you'll just compute the same thing over and over again. On a more serious note: get_fact(0)
will give you 0, which it shouldn't. Prepare your function for this case!
In get_fib
:
function [ F ] = get_fib( k )
if k < 0
fprintf('positive integer please')
end
k = k + 1;
F(1) = 0; % 0th Fibonacci term
F(2) = 1; % 1st Fibonacci term
F(3) = 1; % 2nd Fibonacci term
i = 4;
while k >= i
F(i) = F(i-1) + F(i-2);
i = i + 1;
end
F = F(k)
end
you print a message if k<0
, but you don't do anything extra afterwards. This should be an error message of sorts, so you should either use error
instead of fprintf
, or write F=NaN; return
after fprintf
to prematurely return from the function (without an official error). Otherwise this function seems fine to me.
Now, if you save get_fact
into get_fact.m
and get_fib
into get_fib.m
somewhere on your MATLAB path (which always includes the current directory), you can call them as get_fact(3)
and similar for get_fib()
as you tried.
But your call is also problematic:
for i = 0:n
e = prod(1 / get_fact( i ))
end
here you would call again e = prod(1 / get_fact( i ))
for each i
, in each step overwriting e
. You obviously don't want this. You should either define a vector in place of e
and sum its contents in the end, or keep incrementing the value of your scalar e
in each iteration (but then you have to initialize it to 0). And prod(1/get_fact(i))
will just give you 1/get_fact(i)
since this quantity is a scalar. You would need a sum in any way, and you would have to do it in a different way (see a few sentences earlier).
The tolerance your teacher speaks about is related to the cut-off of the loop where you increment the value of e
, i.e. the approximation to the infinite sum. First you can just take a given maximum order of the approximation, and if it works as it should then you can work on implementing the tolerance.