MATLAB: Drawing a graph from a rational function. What is the problem in the code

drawfunctiongraphplotrational

I want to draw the graph of function f(x)=x^2-1/x^2-4
This is my code:
clear
clf
f=@(x)((x.^2)-1)./((x.^2)-4);
xa=-10; xb=10; s=0.05; ya=-5; yb=5;
xv=linspace(xa,-s); xh=linspace(s,xb);
plot(xv,f(xv),'blue',xh,f(xh),'blue','linewidth',2)
axis equal, axis([xa xb ya yb]), grid on
xlabel('x'), ylabel('y'), title('function')
hold on
However when draw it, it comes out wrong. It has two blue lines where the x asymptotes should be.

Best Answer

It’s necessary to not plot the singularities, then (if you want to), plot the asymptotes there instead. I had to add six lines to replace the singularities with ‘NaN’ values, move the hold line to just below the first plot call, and another two to plot the asymptotes:
f=@(x)((x.^2)-1)./((x.^2)-4);
xa=-10; xb=10; s=0.05; ya=-5; yb=5;
xv=linspace(xa,-s); xh=linspace(s,xb);
yv = f(xv); % Evaluate Function
yh = f(xh);
[mv,vi] = max(yv); % Find Maxima
[mh,hi] = max(yh);
yv(vi) = NaN; % Don’t Connect Singularities
yh(hi) = NaN;
plot(xv,yv,'blue',xh,yh,'blue','linewidth',2)
hold on
plot(xv(vi)*[1 1]', [ya yb]', '--r') % Plot X-Asymptote

plot(xh(hi)*[1 1]', [ya yb]', '--r') % Plot X-Asymptote
axis equal, axis([xa xb ya yb]), grid on
xlabel('x'), ylabel('y'), title('function')
This looks like it does what you want. If you don’t want the asymptotes, don’t include those two lines.