MATLAB: How to create a sine function using a mid point break loop.

midpoint break loopsin

Create a function called my_sin, using a midpoint break loop to approximate the value of sin(x). Determine convergence by comparing successive values of the summation as add additional terms. These successive sums should be within an abs value of 0.001 of each other.
I've tried:
function output = my_sin(x)
x=input('Enter value of x to calculate sin(x): ');
y(1)=x;
total(1)=x;
k=0;
n=0;
while k>=0
k = k+1;
y(k)=(((-1)^k)/(factorial(n)))*x^(n);
total(k) = y(k+1)-y(k);
if (abs(total(k))<=0.001)
break
end
SINX=sum(total);
n=n+2;
end
output = disp(SINX
But I get an error saying:
Attempted to access y(2); index out of bounds because numel(y)=1.
Error in my_sin (line 10)
total(k) = y(k+1)-y(k);
Any help with this would be great.
Thanks

Best Answer

I figured it out; here is in case anyone else would like to see.
function output = my_sin(x)
x=input('Enter value of x to calculate sin(x): ');
k=1;
n=3;
y(1)=x;
total(1)=y(1);
while k>=0
k=k+1;
y(k)=(((-1)^(k-1))/(factorial(n)))*x^((n));
total(k)=total(k-1)+y(k);
if (abs(total(k)-total(k-1))<=0.001)
break
end
n=n+2;
end
l=length(total);
output = total(l);