MATLAB: Does the length of the tangent line keep changing

tangent lines

I'm new to Matlab, and I am making a code to animate the tangent line of sine as it moves along the graph. I am not sure why the length of the line keeps changing as it moves along the curve or how to fix the error I keep getting an error message in line 34 (the one that reads "an.XData = x2;") that states "Invalid or deleted object." Thanks in advance!
Here is my code:
n = 1000;
x = linspace(0,2*pi,n+1);
r = false;
hold on
y = sin(x);
plot(x,y)
hold off
xlim([0 2*pi])
ylim([-1.1 1.1])
x0 = 0;
y0 = sin(x0);
len = 0.7;
m = cos(x0);
theta = atan(m);
x2 = [(x0 + len*cos(theta)), (x0 - len*cos(theta))];
y2 = [(y0 + len*sin(theta)), (y0 - len*sin(theta))];
an = line(x2,y2);
c = an.Color;
an.Color = '#4DBEEE';
i = 1;
while (i <= n)
x0 = (i/n)*2*pi;
y0 = sin(x0);
m = cos(x0);
theta = atan(m);
x2 = [(x0 + len*cos(theta)), (x0 - len*cos(theta))];
y2 = [(y0 + len*sin(theta)), (y0 - len*sin(theta))];
an.XData = x2;
an.YData = y2;
hold on
drawnow
if ~r
i = i + 1;
if i == n
r = true;
end
else
i = i - 1;
if i == 0
r = false;
end
end
end
hold off

Best Answer

"Why does the length of the tangent line keep changing?"
The length is not changing. The reason it appears to change is because the aspect ratio between the x and y axes are not equal so as the line becomes more vertical it is stretched along the y axis since the y axis itself is streched relative to the x axis. To fix that, add this line below before your while-loop.
axis equal
"I keep getting an error message in line 34 (the one that reads "an.XData = x2;") that states "Invalid or deleted object."
That error doesn't occur unless you close your figure while the while-loop is running. The object is deleted when you delete the figure so the an.XData no longer exists.
To prevent that error, add a condition in the while-loop that requires the figure to exist. That will require a few changes:
% 1) at the top of your code
fh = figure(); % you need the figure handle (fh)
% 2) The while-loop should require that the figure exists
while (i <= n) && isvalid(fh)
% 3) Require that the figure exists just before accessing the figure
% Put this just before an.XData = x2;
if ~isvalid(fh)
continue
end
% 4) The 'hold on' should be moved out of the loop, just prior to the loop
% 5) The 'hold off' at the end will create a new, empty figure or will change
% the hold state of the next existing figure. Just get rid of it. If you
% need it, add another condition after the while-loop that checks if the
% figure (fh) exists.