Sie sind auf Seite 1von 17

Plotting graphs 2.

1

2. Plotting graphs
In this section we show how to produce graphs of elementary functions and tables of
data.
2.1 The ez way
The easiest way is to use the ez (pronounced easy) set of commands. Suppose we
wish to plot the graph of ( )
6
cos 2
x
y e x

= then we use ezplot as follows:


Either, (i) using the Symbolic Math Toolbox so we must first define x to be a
symbolic variable.
>> clear all
>> syms x
>> ezplot(exp(-x/6)*cos(2*x))

Figure 2.1. ( )
6
cos 2
x
y e x

= .
ezplot has a default range 2 2 x t t s s so now compare with
>> clear all
>> syms x
>> ezplot(exp(-x/6)*cos(2*x), [0, 8*pi])
Plotting graphs 2.2

Or, (ii) not using the Symbolic Math Toolbox we can use ezplot without prior
definition of the variable as being symbolic. However, in this case we must enclose
the function to be plotted in single quotes ' and '.
>> clear all
>> ezplot('exp(-t/6)*cos(2*t)')

Figure 2.2. ( )
6
cos 2
t
y e t

= .
To change the scale on the y-axis use the Axes Properties in the Edit drop-down
menu in the Figure window.
Very often we use polar coordinates ( ) , r u to define a point in the plane, where r is
the distance from the origin and u is the angle, measured counterclockwise, from the
x-axis. The relationship between Cartesian and polar coordinates is given by
cos and sin x r y r u u = = .
We can produce polar plots using ezpolar as follows:
The cardioid has polar equation 1 cos , with 0 2 r u u t = + s s shown in Figure 2.3
Plotting graphs 2.3

>> ezpolar('1+cos(theta)')

Figure 2.3. The cardioid 1 cos r u = + .

We summarise these procedures in the next section. However, before we do we shall
explain how to copy a figure into a word-processed document.
We frequently need to obtain a copy of a figure for future use. e.g. we may wish to
incorporate the picture into a word-processed report. Also, the diary command does
not capture figures, to save a figure to incorporate into a log of a session we must
copy the figure to a suitable file. We proceed as follows: Copy the picture to the
clipboard, e.g for inclusion into a Word file, by clicking on the Edit menu in the
Figure window and choosing Copy Figure to cut the picture. Finally paste the picture
into the document using Paste in the Edit menu.

2.2 Plotting elementary functions
Suppose we wish to plot a graph of ( ) cos 3 y x t = for 0 1 x s s . We do this by
sampling the function at a sufficiently large number of points and then joining up the
points ( ) , x y by straight lines. Suppose we take 1 N + equally-spaced points, distance
h apart:
Plotting graphs 2.4

>> N=10; h=1/N; x=0:h:1;
defines the set of points 0, , 2 ,...,1 x h h = with 0.1 h = . The corresponding values of y
are computed by
>> y=cos(3*pi*x);
and finally, we can plot the points with
>> plot(x,y)
Figure 2.1. Graph of ( ) cos 3 y x t = for 0 1 x s s using 0.1 h = .

We notice that the graph is a poor representation of the function because the value of
N is too small. So lets change the value of N to 100:
>> N=100; h=1/N; x=0:h:1;
>> y=cos(3*pi*x); plot(x,y)
we obtain the picture shown in Figure 2.2.
Plotting graphs 2.5

Figure 2.2. Graph of cos3 y x t = for 0 1 x s s using 0.01 h = .

We shall now plot ( )
6
cos 2
x
y e x

= in the range 0 8 x t s s . We have two functions


6 x
e

and ( ) cos 2x . Since we shall set up a vector of points for the plot we must use
the array multiplication operator .*.
>> N=200; h=1/N; x=0:h:8*pi;
>> plot(x,exp(-x/6).*cos(2*x), 'r-')
The plot is shown in Figure 2.3.
Plotting graphs 2.6


Figure 2.3. ( )
6
cos 2
x
y e x

=
There is an alternative approach in which MATLAB chooses the points within a given
range. We give the commands which plot the same function:
>> clear all
>> fplot('exp(-x/6)*cos(2*x)', [0, 8*pi])
Notice the use of the single quotes ' and ' to delimit the string defining the function
to be plotted. In this case we use the standard multiplication operator *.
Finally, a third possibility uses ezplot, which uses the Symbolic Math Toolbox so we
must first define x to be a symbolic variable. ezplot has a default range
2 2 x t t s s .
>> clear all
>> syms x
>> ezplot(exp(-x/6)*cos(2*x))
Now compare with
>> clear all
>> syms x
>> ezplot(exp(-x/6)*cos(2*x), [0, 8*pi])
We now give an example illustrating choice of graph title, line and marker styles and
axes and title labels.
Open the m-file temperature.mat.
Plotting graphs 2.7

The m-file contains a set of temperature values, T, described by the variable temp, at
corresponding times, t, described by the variable time. We shall plot this data
together with an approximating sine wave ( ) 17.5 5.5sin 0.5 T t = + .
To open the file:
Either, click on open file on the toolbar then double click on temperature.
MATLAB will reply with
Variables created in workspace
>>
Type temp in response to the prompt and the data set of temperatures will be shown.
>> temp
temp =
13
13
12
.
.
.
21
21
20
19

Or, type
>> load temperature
MATLAB provides no response but type temp as above and the data will be shown on
screen as above.
We shall now plot the data and annotate the graph:
>> plot(time,temp, 'ro-') % red circles, solid line
>> hold on % allow another graph on the same plot
>> y=17.5+5.5*sin(0.5*time);
>> plot(time,y,'k*:') % black stars, dotted line
>> xlabel('\fontname{Courier New}{Time (hours)}') % Courier New font
>> ylabel('\fontname {Courier New}{Temperature (^oF)}')
>> title(['\fontsize{14}{Temperature (solid red), sine (dotted
black)}'])
>> text(1350,19,'\it{Temperature data}') % italic style, at
(1350,19)
>> text(1050,21,'\it{sine wave}')
Plotting graphs 2.8

and the graph is shown in Figure 2.4.

Figure 2.4. Data in file temperature.mat.

This example illustrates how to annotate graphs and how to choose the style and
colour. We summarise these procedures in the next section. However, before we do
we shall explain how to copy a figure into a word-processed document.
We frequently need to obtain a copy of a figure for future use. e.g. we may wish to
incorporate the picture into a word-processed report. Also, the diary command does
not capture figures, to save a figure to incorporate into a log of a session we must
copy the figure to a suitable file. We proceed as follows: Copy the picture to the
clipboard, e.g for inclusion into a Word file, by clicking on the Edit menu in the
Figure window and choosing Copy Figure to cut the picture. Finally paste the picture
into the document using Paste in the Edit menu.

2.3 Summary of plotting procedures
Plotting titles and labels
To insert a title and label the axes, we use
>> title('plot of y=cos(3pi*x)')
>> xlabel('x-axis'), ylabel('y-axis')
The strings enclosed in single quotes for the title and axis labels can be anything we
wish.
Plotting graphs 2.9

Grids
A dotted grid may be added by
>> grid
This can be removed using either grid again or grid off.
Line styles and colours
The default is to plot solid lines. A solid red line is produced by
>> plot(x,y,'r-')
The third argument is a string whose first character specifies the colour (optional) and
the second the line style. The options for colour and styles are shown in Table 2.1.

Table 2.1. Colours and line styles.
Colours Line styles
y
m
c
r
g
b
w
k
yellow
magenta
cyan
red
green
blue
white
black
.
o
x
+
-
*
:
-.
--
point
cirlce
x-mark
plus
solid
star
dotted
dashdot
dashed

Multi-plots
Several graphs may be drawn on the same figure and we may include a descriptive
legend as in
>> N=100; h=1/N; x=0:h:1;
>> y=cos(3*pi*x); z=sin(3*pi*x);
>> plot(x,y,'g-',x,z,'b--')
>> legend('cos','sin')
>> title('multi-plot')
and the plot is shown in Figure 2.5.
Plotting graphs 2.10

Figure 2.5. Multi-plot with legend.

The legend gives a list of line-styles, as they appeared in the plot command, followed
by a brief description. MATLAB fits the legend in a suitable position, so as,
whenever possible, not to conceal the graphs.
Hold
A call to plot clears the graphics window before plotting the current graph. This is
not convenient if we wish to add further graphics to the figure at some later stage. To
stop the window being cleared:
>> plot(x,y,'g-'), hold
Current plot held
>> plot(x,z,'b--'), hold off
hold on holds the current picture; hold off releases it (but does not clear the
window, which can be done with clf). hold on its own toggles the hold state.
Subplot
The graphics window may be split into an m n array of smaller windows into which
we may plot one or more graphs. The windows are counted 1 to mn row-wise,
starting from the top left. Both hold and grid work on the current subplot.
subplot(221) or subplot(2,2,1) specifies that the window should be split into a
2 2 array and we select the first subwindow etc.
>> clear all
>> N=100; h=1/N; x=0:h:1;
Plotting graphs 2.11

>> subplot(2,2,1), plot(x,cos(pi*x))
>> subplot(2,2,2), plot(x,cos(2*pi*x))
>> subplot(2,2,3), plot(x,cos(3*pi*x))
>> subplot(2,2,4), plot(x,cos(4*pi*x))
and the four plots are shown in Figure 2.6.
Figure 2.6. Four subplots.

Zooming
We often need to zoom in on some portion of a plot in order to see more detail.
This is easily achieved using the command
>> zoom
Pointing the mouse to the relevant position on the plot and clicking the left mouse
button will zoom in by a factor of two. This may be repeated to any desired level.
Clicking the right mouse button will zoom out by a factor of two.
Holding down the left mouse button and dragging the mouse will cause a rectangle to
be outlined. Releasing the button causes the contents of the rectangle to fill the
window. zoom off turns off the zoom capability.
We can use the zoom facility to estimate the solution of a pair of equations as follows:
Consider the pair of equations 3 and 2
x
y e y x

= = for 0 5 x s s . We plot them in


the same window
>> clear all
>> x=0:0.05:5; y=3*exp(-x); z=x/2;
>> plot(x,y,'b-',x,z,'k-')
Plotting graphs 2.12

and use zoom to find that the point of intersection is approximately ( ) 1.432, 0.7162
giving the approximate root as 1.43. Verify that this root is correct to two decimal
places.

Controlling axes
Once a plot has been created in the graphics window we often wish to change the
range of x and y values shown on the picture.
>> clf % clears the figure window
>> clear all
>> N=100; h=1/N; x=0:h:1;
>> y=cos(3*pi*x); plot(x,y)
>> axis([0.1 1.2 -1.1 1.1])
The first two parameters are the minimum and maximum values of x to use on the
axis and the last two are the minimum and maximum values of y. Note the square
brackets. The result of these commands is shown in Figure 2.7.
Figure 2.7. The effect of changing the axes.

Other useful axes commands are axis('equal'), axis('auto'),
axis('square'), axis('normal').
Parametric plots
A parametric equation of the cycloid is given by sin , 1 cos x t t y t = = with
0 2 t t s s . We can develop the parametric plot as follows:
Plotting graphs 2.13

>> t=0:0.01:2*pi; x=t-sin(t); y=1-cos(t); plot(x,y)
The plot is shown in Figure 2.8
Figure 2.8. The cycloid sin , 1 cos x t t y t = = .

2.4 Comets
Try
>> clear all
>> N=500; h=1/N; x=-pi:h:pi;
>> comet(x,tan(sin(x))-sin(tan(x)))
and
>> N=500; h=1/N; x=-pi:h:pi;
>> comet3(cos(5*x),sin(5*x),x)

2.5 Plotting surfaces
A surface is defined by a function ( ) , f x y . Corresponding to each value of ( ) , x y we
compute the height of the function by ( ) , z f x y = .
The surface equivalents of the ez plot family are ezcontour, ezcountourf, ezsurf
and ezsurfc.
Consider the surface defined by the function
( ) ( ) ( )
2 2
, 3 2 f x y x y =
for 2 4 and 1 3 x y s s s s .
>> ezsurf('(x-3)^2-(y-2)^2', [2,4], [1,3])
Plotting graphs 2.14

The plot is shown in Figure 2.9

Figure 2.9. Saddle function ( ) ( ) ( )
2 2
, 3 2 f x y x y = .
We can produce a contour plot:
>> ezcontour('(x-3)^2-(y-2)^2')
as shown in Figure 2.10.
Figure 2.10. Contour plot of the saddle function ( ) ( ) ( )
2 2
, 3 2 f x y x y = .

Plotting graphs 2.15

The ez family of surface plots is the easiest way forward if we wish to produce a
plot quickly. If we wish more control over the plot then we proceed as follows:
We may wish to prescribe the ranges of x and y, we then need to choose a grid on this
domain. Finally, we must evaluate the function at each point of the grid and plot it.
Consider the saddle surface above
( ) ( ) ( )
2 2
, 3 2 f x y x y =
for 2 4 and 1 3 x y s s s s .
>> [x,y]=meshgrid(2:0.2:4, 1:0.2:3);
>> z=(x-3).^2-(y-2).^2;
>> mesh(x,y,z)
The surface ( ) , z f x y = is shown the in Figure 2.101

Figure 2.11. Plot of saddle function.

We now consider the function

( )
2 2
2 x y
z xye
+
= for 2 2, 2 2 x y s s s s .
>> [x,y]=meshgrid(-2:0.2:2, -2:0.4:2);
>> z=-x.*y.*exp(-2*(x.^2+y.^2));
>> mesh(x,y,z)
and the surface plot is shown in Figure 2.12.

Plotting graphs 2.16


Figure 2.12. Surface plot.
We obtain contour plots as follows:
>> [x,y]=meshgrid(-2:0.1:2, -2:0.2:2);
>> z=-x.*y.*exp(-2*(x.^2+y.^2));
>> contour(x,y,z)
Figure 2.13. contour plot.

Plotting graphs 2.17

Sometimes we wish to change the edge colours on a surface plot or we may wish to
have a plot without the default background. For example we may wish to have no
background and black edge colour, as shown in Figure 2.9, for the function
( ) ( ) ( )
2 2
, 3 2 f x y x y = with 2 4 x s s and 1 3 y s s .
Figure 2.14. ( ) ( ) ( )
2 2
, 3 2 f x y x y = .
We can obtain the picture as shown in Figure 2.13 as follows:
Edit Current object properties Color Edge color Black
Edit Figure properties OK
Edit Copy options Force white background

2.6 Copying to and from Word
To copy a sequence of MATLAB commands and results to a Word file, open a
suitable document with MATLAB open. Select the MATLAB section, copy it onto
the clipboard, then paste it directly into the Word file. The process of copying from a
Word file to MATLAB is similar except that you can copy only to the prompt line.
To copy a plot into a Word file see the example temperature.mat in section 2.1.

2.7 Hard copy
To obtain a printed copy simply copy your plot(s) to a Word file as described in the
MATLAB Exercise section. The Word file can then be printed in the usual way.

Das könnte Ihnen auch gefallen