I am currently trying to plot tan(x)=x in Matlab but with the y=x portion only crossing the tan(x) at the intersection points.
Here is what I am trying to recreate in Matlab shown in Desmos:
As you can see, I have defined the domain to be $x,\:\left\{n\pi <x<\left(n+\frac{1}{2}\right)\pi \right\}$
Now here is my plot in Matlab:
As you can see, my lines do not cross the tan(x) like it dose in demos, but I cant really understand why. Here is my Matlab code:
f=@(x) tan(x); % defining an anyloums fucntion for tan(x)
%using a for loop to specifically show the y=x a lines of length of the
%given domian
for n=0:1:10;
x=(n*pi:(n+1/2)*pi);
y=x;
plot(x,y)
hold on;
fplot(f,[0,11*pi])
end
The reason that I am doing this is because of a question that I have been given which is shown below.
By plotting the functions or otherwise, show that the equation tan( x ) = x has an infinite number of solutions $x_n$ where , $x_n,\:\left\{n\pi \le x_n\:\le \left(n+\frac{1}{2}\right)\pi \right\}$


You have an interesting programmation error :
It comes from the fact that you have written
x=n*pi:(n+1/2)pi
Let us consider for example the case $n=1$. What this instruction generates is
$x=[3.1416 , 4.1416]$
The lower bound is correct, the upper bound isn't (it should be $3\pi/2=4.7124$)
Why that ? Because you have omitted to give a step like $0.01$ in x=n*pi:0.01:(n+1/2)pi.
Thus, what happens ? The default step is one ; thus, what Matlab does is
Begin by the left bound : $3.1416$, OK, then add the step
$3.1416+1=4.1416$ OK because this value is below limit $4.7124$, but,
$3.1416+1+1=5.1416$ is above limit $4.7124$, thus isn't considered.
We are left with the two values $3.1416$ and $4.1416$...
Here is a way to correct your program :
You can observe that :
the range has been transformed into x=n*pi:0.01:(n+1/2)*pi; as announced.
plotting $f$ has been externalized from your loop.
Besides :
You could have used a comma instead of a colon (very valuable remark by @Lutzl) :
x=[n*pi$\color{red}{,}$ (n+0.5)*pi]; y=x; plot(x,y);
I think that you can achieve a better vizualization by reconsidering your issue as the intersection of curves with equations
$$y=\frac{\tan(x)}{x} \ \ \ \ \text{and} \ \ \ \ y=1$$
(see figure below) with the advantage to have points of interest (intersection points) all situated at the same level, closer and closer to the asymptotes with equations $(n+\frac12)\frac{\pi}{2}$.