Plotting Functions of a Single Variable in Matlab

This document is a working document. It is expected that you are sitting in front of a computer terminal where the Matlab software is installed. You are not supposed to read this document as if it were a short story. Rather, each time your are presented with a Matlab command, it is expected that you will enter the command, then hit the Enter key to execute the command and view the result. Furthermore, it is expected that you will ponder the result. Make sure that you completely understand why you got the result you did before you continue with the reading.

Getting Started

Matlab excels at plotting graphs of functions. Much of this manual is dedicated to drawing the graphs of the various functions encountered in a multivariable calculus course. However, you have to walk before you can run, so we will begin with basic plotting techniques and move toward more advanced technique in subsequent activities.

In this section we will learn how to draw the graph of a single-valued function of one real variable; i.e., a function defined by a rule or equation such as y = f (x). We begin with a definition.

Let f: R→R be defined by the rule y = f (x). The graph of f is defined as:

Graph of f = {(x,f(x)): x is in the domain of f}

Alternatively, the graph of f is the set of all points (x,y), such that y = f(x) for some x in the domain of f .

The idea is simple: the graph of f is the set of all points (x,y) that satisfy the equation y = f(x). Consequently, a standard graphing technique is to create and plot table of points that satisfy the equation. An example should make this clear.

Use Matlab to sketch the graph of f(x) = x2.

Solution: If we were plotting this graph by hand, we would start by selecting values for the independent variable x that lie in the domain of f . We would place these values in the first column of a table, similar to Table 1. Then, for each value of x, we would calculate the corresponding function value with equation f(x) = x2, placing the results in the second column of the table as we work. Finally, we would set up a coordinate system on a sheet of graph paper and plot each of the points in Table 1.

x -3 -2 -1 0 1 2 3
f(x)=x2 9 4 1 9 1 4 9

A collection of points satisfying f(x)=x2

But how would one accomplish this task in Matlab? We could begin by creating a list of x-values.

>> x=[-3 -2 -1 0 1 2 3]
x =
-3 -2 -1 0 1 2 3

Next, we wish to square each value in this list. The natural thing to try is x2, but that won't work.

>> x^2
??? Error using ==> mpower
Matrix must be square.

Remember, in Matlab, x2 means x*x. You cannot multiply these lists because their dimensions won't accommodate matrix multiplication. However, we don't want to square the list; we want to square each element in the list. Thats what array exponentiation is for!

>> y=x.^2
y =
     9     4     1     0     1     4     9

There are two things to note: (1), array exponentiation squared each element of the list x, and (2), weve stored the result of this operation in the variable y for future use. This allows us to easily plot each of the data points provided in the lists x and y. The command

>> y=x.^2
y =
     9     4     1     0     1     4     9

will plot the image shown in Figure 1.

A plot of the points in Table 1.

A plot of the points in Table 1.

The command plot(x,y,'o') warrants some explanation. The command plot(x,y,s) plots list y versus list x; i.e., Matlab plots all ordered pairs (u,v), where u is taken from list x and v is taken from list y. The character string s determines the symbol used for plotting. In our case, s='o', which instructs Matlab to use a small, unfilled circle to plot each point. Other plotting symbols are available. For example, try plot(x,y,'+'), plot(x,y,'*'), or plot(x,y,'s'). A full list of plotting symbols is given in the help file for the plot command (type help plot to obtain a full explanation of the plot command).

Thus far, we've only plotted seven points that satisfy the equation f(x) = x2, but Definition 1 requires that we plot all points satisfying the equation y = f(x). We need to plot more points.

Matlab provides the construct start:increment:stop for creating lists of equally spaced values. The command

>> x=-3:.5:3
x =
  Columns 1 through 7 
   -3.0000   -2.5000   -2.0000   -1.5000   -1.0000   -0.5000         0
  Columns 8 through 13 
    0.5000    1.0000    1.5000    2.0000    2.5000    3.0000

creates a list whose first entry is -3, the second entry is -2.5, and so on, up to and including (in this case) 3. (The output of this command warrants some explanation. The vector x has length 13 (check this with length(x)), but it is a row vector, one row and thirteen columns. Of course, there is not enough room to fit thirteen columns across the screen, so part of the list is put on a second row, with a heading to indicate that you are seeing columns 8 through 13. If you find this terribly distracting, try taking the transpose, x=x', then enter y=x.^2. Sometimes incrementing will fall short of the stop value, as in x=-3:.7:3. Try it!)

Square each element in the list x and store the result in the list y.

>> y=x.^2
y =
  Columns 1 through 7 
    9.0000    6.2500    4.0000    2.2500    1.0000    0.2500         0
  Columns 8 through 13 
    0.2500    1.0000    2.2500    4.0000    6.2500    9.0000

Now you can plot the graph, as shown in Figure 2, with

>> plot(x,y,'o')

Adding more points to the plot.

Adding more points to the plot.

We still haven't plotted all points satisfying the equation f(x) = x2, so we're not finished. The commands

>> x=-3:.1:3
>> y=x.^2
>> plot(x,y,'o')

increment entries in the vector x by a tenth and produce the plot in Figure 3.

Adding even more points.

Adding even more points.

Clearly, we can't continue in this manner indefinitely. At some point we are going to have to make an assumption about where the rest of the points satisfying y = f(x) will fall.

You can instruct Matlab to connect points in your plot with line segments. The command plot(x,y,'o-') was used to produce the graph in Figure 4(a). Matlab's default plotting command, plot(x,y), connects the points created from list x and y with line segments. If you plot enough points, you will get a smooth looking curve, as shown in Figure 4(b), but if you don't plot enough points, then plot(x,y) will produce a kinky plot like the one shown in Figure 4(c). It is important to note that only the points created by the list x and y satisfy the equation y = f(x). In between points, Matlab is approximating the actual graph with line segments.

Plotting the graph of f(x)=x2.

There are a number of colors, plotting symbols, and line styles available for use with the plot command. The idea is simple: in the command plot(x,y,s), s is a character string used to select the color, plotting symbol, and line style. For example, plot(x,y,'gd-') will use green diamonds for the plotting symbols, then connect each pair of points with a green line segment. Order is irrelevant, so plot(x,y,'-gd') produces exactly the same image. If you don't select a plotting symbol, then one won't be used. For example, plot(x,y,'r--') will connect each pair of points with a red, dashed line segment. A full list of colors, plotting symbols, and line types is available in the help file for the plot command (type help plot).

Let's look at a second example.

Use Matlab to draw the graph of f(x) = x2 - 2x - 3 on the interval [-1, 3].

Solution: Users new to Matlab always struggle with array operations at first. It can be discomforting to work with entire arrays of numbers rather than with the individual numbers themselves. Let's take a slightly different tack on this example in the hopes of adding some clarity to array operations in Matlab.

Suppose that we enter the numbers x1, x2, ... , xn into the equation of the function f to produce the data in Table 2.

x f(x)
x1 x12 - 2x1 - 3
x2 x22 - 2x2 - 3
... ...
xn x2 - 2xn - 3

A collection of points satisfying f(x)=x2

Now, let's look carefully at the vector y=x.^2-2*x-3. Technically, we immediately have a problem, because you cannot subtract the scalar number 3 from a vector. However, since this type of operation is so common, Matlab is forgiving and allows it. In fact, if you subtract three from a vector in Matlab, Matlab will subtract 3 from each entry of the vector (e.g., try [3,3,3]-3 and see what happens). Consequently, the computation

produces the second column of Table 2 and stores it in the variable y. Hopefully, it should now be clear why the commands

>> x=-1:.1:3
>> y=x.^2-2*x-3
>> plot(x,y)

produce the graph shown in Figure 5.

It is important to label the axes of your graph. You might also need a grid and a title. This is easily done in Matlab. The commands

>> xlabel('x-axis')
>> ylabel('y-axis')
>> title('The graph of f(x) = x^2 -2x - 3')
>> grid on

produce the axes labels, title, and grid shown in Figure 5 (Matlab recognizes a small subset of TeX commands. So typing title('x^2') produces a superscript, while title('x_2') produces a subscript. If you need more than one character in your sup/subscript, enclose it in curly braces, as in title('x^{2\alpha}').).

The graph of f(x)=x^2-2x-3.

The graph of f(x) = x2 - 2x - 3.

Two or More Plots

The plot command can draw more than one graph at a time. If you have data in x1, y1, x2, y2, ... , xn, yn, then the command plot(x1,y1,s1,x2,y2,s2,...,xn,yn,sn) will plot the data using the line style s1 for the data in x1, y1, etc.

Sketch the graphs of f(x) = 1/x and g(x) = ln(x - 1) on the interval [2, 5].

Solution: Use the functions f and g to calculate data for the two plots.

>> x=2:.1:5
>> f=1./x
>> g=log(x-1)

Two comments are in order. First, Matlab's command for the natural logarithm is log (base two and base ten logarithms are also available as log2 and log10.). Secondly, it is highly illegal to divide a scalar by a vector, as any mathematician will tell you. So the command, f=1./x is perplexing, to say the least. Technically, we should enter ones(size(x))./x, which makes a lot more sense, but this is such a common operation that Matlab makes a special interpretation in this case. That is, Matlab takes 1./x to mean: "form a vector whose first element is computed by dividing 1 by x(1), whose second element is computed by dividing 1 by x(2), etc.", exactly what we want.

Now, the command

>> plot(x,f,x,g)

will produce a plot containing the graphs of both f and g on the desired interval. Matlab also cycles through a default set of colors, automatically coloring each graph with a different color. The command

>> plot(x,f,'-',x,g,'--')

plots the graphs of f and g with different linestyles, f with a solid line, g with a dotted line, useful if you don't have a color printer. Finally, when plotting more than one graph, it is good form to create a legend to help distinguish the plots. The command

>> legend('f(x) = 1/x', 'g(x) = ln(x-1)')

was used to create the image shown in Figure 6.

The graphs of <i>f(x) = 1/x</i> and <i>g(x) = ln(x-1)</i>.

The graphs of f(x) = 1/x and g(x) = ln(x-1).

Exercises

Use Matlab's plot command to draw the graphs of the functions in exercises 1-4 on the given interval. Label each axis and provide a title for your plot.

  1. f(x) = 5 - 4x - x2 on [-6,2]
  2. f(x) = 2x2 - 8x - 11 on [-1,5]
  3. f(t) = t e-2t on [-1,5]
  4. h(t) = e-0.1t sin(2t) on [0,24π]

Hint: In exercise 4, enter h=exp(-0.1*t).*sin(2*t). Remember, you cannot multiply vectors, so you need to use array multiplication in this exercise.

In each of exercises 5-8, use Matlab's plot command to draw both functions on the same axes, drawn on the given interval. Label each axis. Provide a title and legend for your plot.

  1. s(x) = cos(2x) + sin(3x), v(x) = -2sin(2x) + 3cos(3x), on [0,4π].
  2. f(x) = x e-3x, g(x) = e-3x (1 - 3x), on [0,2].
  3. f(t) = sin(3t)cos(2t), g(t) = (1/2) cos(t) + (5/2) cos(5t), on [0,4π].
  4. x(t) = (1 + 2sin(t)) cos(t), y(t) = (1 + 2sin(t)) sin(t), on [0,2π].

Hint: In exercise 8, enter x=(1+2*sin(t)).*cos(t) and y=(1+2*sin(t)).*sin(t). Remember, you cannot multiply vectors, so you need to use array multiplication in this exercise.

Matlab Files

Although the following file features advanced use of Matlab, we include it here for those interested in discovering how we generated the images for this activity. You can download the Matlab file at the following link. Download the file to a directory or folder on your system.

plotting.m

The file plotting.m is designed to be run in "cell mode." Open the file plotting.m in the Matlab editor, then enable cell mode from the Cell Menu. After that, use the entries on the Cell Menu or the icons on the toolbar to execute the code in the cells provided in the file. There are options for executing both single and multiple cells. After executing a cell, examine the contents of your folder and note that a PNG file was generated by executing the cell.