


Part 5: Graphing Functions
All of the standard mathematical functions, plus many other functions, are available in MATLAB. Functions operate both on both single numbers and on vectors. You can use MATLAB just like a calculator.
The standard method of graphing functions in MATLAB requires you to make lists
(really vectors) of x values and y values and then give the command
to plot the (x,y) pairs. You can get a list of x values covering the
range you need by using a command of the form:
x = xstart: xincrement: xend .
Below, we plot the builtin function y = exp(x) on the interval from –1 to 2.
x = 1: 0.1: 2
y = exp(x)
plot(x, y)
Usually, we don’t want to print out the x and y lists so we use a semicolon to suppress the output.
We can control the graph's color and line style by adding an extra parameter to the plot command. Choices for colors are 'c' (cyan), 'm' (magenta), 'y' (yellow), 'r' (red), 'g' (green), 'b' (blue), 'w' (white), and 'k' (black). Line style choices are '' for solid (the default), ' ' for dashed, ':' for dotted, and ' .' for dashdot. Let's make the graph red and dotted.
x =  4: 0.5: 3;
y = cos(x);
plot(x, y, 'r:')
MATLAB has marker types '+', 'o', ' * ', and 'x' and the filled marker types 's' for square, 'd' for diamond, '^' for up triangle, 'v' for down triangle, '<' for right triangle, '>' for left triangle, 'p' for pentagram, and 'h' for hexagram. If you specify a marker but not a line style, your graph only has disconnected markers. Here we plot blue diamonds.
Using unconnected markers is just what we want in order to produce a scatterplot of data points. Rarely do we want such points connected by lines.
x = [1, 2, 4, 5, 7]
y = [10,  4, 3, 1, 6]
plot(x, y, 'ro')
We can plot more than one graph on a single plot by using the hold on command to save the old plot and then make another plot the usual way. Below, we add the line y =  3*x + 15 to the last scatterplot.
hold on
x = 1: 0.2: 7;
y =  3*x + 15;
plot(x, y, 'b')
There are additional commands that allow us to control the "window" of the graph, add grid lines, put labels on the axes, add a title for the graph, and specify a legend. We will add these features to our plot.
% Window: 1 < x < 7,  5 < y < 1
axis( [1, 7,  5, 11] )
grid on
xlabel( 'x values' )
ylabel( 'yaxis' )
title( 'Plot of y versus x' )
legend( 'data points', 'line')
There is another, sometimes easier, way to make a plot in MATLAB; using the fplot function. You simply put the name of your function in single quotes. You can use line markers for the curve like ' +', ' x', ' o', and ' *'. You have no choice of color and generally have less control over the appearance of the plot. To find out more about features of fplot, type "help fplot" at the MATLAB prompt.
clf % clears figure window
fplot('sin(x)', [ 3, 3])
grid on
Experiment with combinations of the commands used for plotting to be sure you feel comfortable using them.



modules at math.duke.edu
Copyright
CCP and the author(s), 2000