MATLAB: Trouble getting the correct graph

asymptotesgraph

I am having trouble obtaining the correct graph for the given problem:
Plot the function f(x)= (0.5x^3-x^2)/(x^2-x-20) for -15=<x=<15. Notice that the function has two vertical asymptotes. Plot the function by the domain of x into three parts: one from -15 to near the left asymptote, one between the two asymptotes, and one from near the right asymptote to 15. Set the range of the y-axis from -20 to 20.
I thought my script would be correct, but the graph is totally wrong. Any help is greatly appreciated. Thank you in advance! Here is my script:
% Plot f(x)= (0.5x^3-x^2)/(x^2-x-20)
clear all
% Create an array of x-values for -15<x<-4
x1= -15:0.05:-4.1;
% Create an array of x-values for -4<x<5
x2= -3.9:0.05:4.9;
% Create an array of x-values for 5<x<15
x3= 5.1:0.05:15;
% Create y-values for -15<x<-4
y1=(0.5*x1.^3-x1.^2)/(x1.^2-x1-20);
% Create y-values for -4<x<5
y2=(0.5*x2.^3-x2.^2)/(x2.^2-x2-20);
% Create y-values for 5<x<15
y3=(0.5*x3.^3-x3.^2)/(x3.^2-x3-20)
% Multiple plots on one set of axes
plot(x1,y1,x2,y2,x3,y3)
% Plotting limits for the x-axis and y-axis
axis([-15 15 -20 20])

Best Answer

First, I would suggest that you use an Anonymous Function for ‘f’. They make life immeasurably easier in situations such as yours.
Second, you need to do element-by-element division, as well as exponentiation. Use (./) instead of (/) here.
A slightly shorter version of your code seems to work for me:
f = @(x) (0.5*x.^3-x.^2)./(x.^2-x-20); % Anonymous Function For ‘f’
x = -15:0.1:15;
y = f(x);
figure(1)
plot(x, y)
grid
You can create your ‘x1’ and ‘y1’ and other vectors just as you did in your original code, just easier. Use the one anonymous function version for ‘f’ to calculate all your ‘y1’ from ‘x1’ and so for the rest.
Related Question