Jack - part of the problem may have to do with the equation. You state that you are trying to _find the sum of series (-1)^n * (x^2n+1)/(2n+1)! _. Do you really mean this to be
(-1)^n * (x^(2*n+1))/(2*n+1)!
where the exponent of x is 2*n+1? The line of code that is written as
means that the exponent of x is 2*i (I think it more likely that the exponent is considered as 0.0000 + 2.0000i - see below for details), and added to that result is 1/z when what you want instead is x to the power of 2*i+1 and that result divided by z.
The other problem, like you suggest, has to do with the factorial. Your code for this term is z and it is initialized as
which is a vector of integers from 1 to 1 with a step-size of 2*i+1. So it will always be just one. Use the factorial function instead which will sum the product of the integers from 1,2,...,2*k+1.
This changes your code to
function [S] = taylorTerm1(x,n)
S = 0;
kTerm = (-1)^(k)*(x^(2*k*+1))/factorial(2*k+1);
S = S + kTerm;
Note the differences. I've removed the initialization of
since this overwrites the input parameter with a vector. This will cause confusion for the line
and will probably cause the iterations to terminate early.
I've replaced the i with k since MATLAB uses i and j to represent imaginary numbers. In your code, where there was 2i, this was probably being considered as the imaginary number 0.0000 + 2.0000i and not the desired 2*i.
The kterm has been reworked to something more like what you want, and the summation term was changed so that we were always summing S with the values from the previous iterations and the current iteration.
Try the above and see what happens!