Department of Engineering

IT Services

2D Graphics

MATLAB can be used to plot 1-d functions. Consider the following problem:


Find to 3 d.p. the root nearest 7.0 of the equation 4x3 + 2x2 - 200x - 50 = 0

MATLAB can be used to do this by creating file eqn.m in your matlab directory:


function [y] = eqn(x)

% User defined polynomial function
[rows,cols] = size(x);
for index=1:cols
y(index) = 4*x(index)^3+2*x(index)^2-200*x(index)-50;
end

The first line defines `eqn' as a function - a script that can take arguments. The square brackets enclose the comma separated output variable(s) and the round brackets enclose the comma separated input variable(s) - so in this case there's one input and one output. The % in the second line means that the rest of the line is a comment. However, as the comment comes immediately after the function definition, it is displayed if you type :


>> help eqn

The function anticipates x being a row vector so that size(x) is used to find out how many rows and columns there are in x. You can check that the root is close to 7.0 by typing:


>> eqn([6.0:0.5:8.0])

Note that eqn requires an argument to run which is the vector [6.0 6.5 7.0 7.5 8.0].

The for loop in MATLAB should be avoided if possible as it has a large overhead. eqn.m can be made more compact using the . notation. Delete the lines in eqn.m and replace them with:


function [y] = eqn(x)

% COMPACT user defined polynomial function
y=4*x.^3+2*x.^2-200*x-50;

Now if you type ` eqn([6.0:0.5:8.0])' it should execute your compact eqn.m file.
Now edit and save ploteqn.m in your matlab directory:


x_est = 7.0;

delta = 0.1;
while(delta > 1.0e-4)
x=x_est-delta:delta/10:x_est+delta;
fplot('eqn',[min(x) max(x)]);
grid;
disp('mark position of root with mouse button')
[x_est,y_est] = ginput(1)
delta = delta/10;
end

This uses the function fplot to plot the equation specified by function eqn.m between the limits specified. ginput with an argument of 1 returns the x- and y-coordinates of the point you have clicked on. The routine should zoom into the root with your help. To find the actual root try matlab's solve routine:


>> poly = [4 2 -200 -50];

>> format long
>> roots(poly)
>> format

which will print all the roots of the polynomial : 4x3 + 2x2 - 200x - 50 = 0 in a 15 digit format. format on its own returns to the 5 digit default format.