In the Homework function, there are two Taylors - the nx1 vector local variable
and the function
This causes a conflict at the line where the function is called and the result is assigned to the vector
Variables and functions cannot have the same name. I recommend changing the local variable to
or removing it altogether since it doesn't seem to be used outside of the for loop.
Note that the Taylor function has a return value of y but never initializes this value, but there is an f that is summed at each iteration so this should be replaced with y (or vice versa) else there will be an error. Also the second input parameter n is unused. It may be that it should be used in the for loop
as this would give results that show that the error is reduced between the exact function and the Taylor series approximation as the number of terms in the latter is increased. Further, y (or f) should be initialized as
rather than as 1 (even though it results in the same answer) just to be clear that our a or c is zero (is this true - that a is zero in this Taylor series expansion and so is the Maclaurin series?). And…I think that the exponent is incorrect on the first term. What we should have is the nth derivative evaluated at a (or c which is zero) which, because the function is exp(-x/4), is just f_exact(a) multiplied by (-1.4)^i. That product is then multiplied by (x-a)^i which is then divided by i!. What I think you really want for this code (based on http://en.wikipedia.org/wiki/Taylor_series) is: function [y] = Taylor(x,n)
a = 0;
y = f_exact(a);
for i=1:n
y = y + f_exact(a)*(-1/4)^i*(x-a)^i/factorial(i);
end
The function f_exact takes as an input parameter x and then immediately redefines it to a row vector with three elements. Why? I think that this line of code and the for loop should be removed as the output is a 10x3 matrix with each row being identical. If the idea is to have f_exact represent exp(-x/4), then that is all it should do:
function y=f_exact(x)
y = exp(-x/4);
end
unless there is some reason why x is replaced with a row vector and the for loop is there. Note that if this isn't changed, then there will be the error In an assignment A(I) = B, the number of elements in B and I must be the same. when assigning taylorVctr(i) = Taylor(x,i);.
Best Answer