• No results found

Problem 15 Consider the matrix

1.2.5 Graphical Functions

One of the outstanding strengths of MATLAB is its capability of graphical visualization of computational results.

For this, MATLAB has available very simple but powerful graphi-cal functions. MATLAB is thus able to represent ordinary functions in two-dimensional plots (xy plots) and functions of two variables in three-dimensional plots with perspective (xyz plots).

A complete survey of all the graphical functions can be obtained by entering help graph2d, help graph3d, and help graphics in the command window or in the corresponding entries of MATLAB help. In this section we shall discuss only the most useful and important of these functions.

Two-dimensional Plots

By far the most important and the most commonly used graphical func-tion is the funcfunc-tion plot. Entering help plot provides the following information (excerpt):

>> help plot

PLOT Linear plot.

PLOT(X,Y) plots vector Y versus vector X. If X or Y is a matrix, then the vector is plotted versus the rows or columns of the matrix, whichever line up ...

MATLAB help (of which we present only part of the full display for rea-sons of space) shows the basic capabilities of plot. Beyond that, there are many other possibilities and options for plot. A discussion of this topic is beyond the scope of this book. The interested reader can look at the book by Marchand.9

As the help function shows, in principle, two vectors are required in order to plot a graph. The first vector represents the vector of x values and the second, the corresponding vector of y values. The vectors must, therefore, have the same length. If this is not so, MATLAB produces an appropriate error message unless x is a scalar (see help plot). This message shows up in practice, even for experienced MATLAB users, but the error is easily corrected.

Many functions can also be plotted simultaneously, either by writing the x, y pairs one after the other in the parameter list or, when the same x vector will always be used, by combining the y vectors into a corresponding matrix.

In addition, the form of the graphs in terms of the type of line and color can be varied by using suitable parameters.

Our first example again uses the variables s and t from the example in Section 1.2.4, and plots the result obtained there:

>> t = (0:1:5);

>> s = sin(t);

>> plot(t,s)

9P. Marchand, Graphics and GUIs with MATLAB, CRC Press, 1999.

Note that in this example numerical output of the variables t and s is suppressed.

The plot command opens a window with the plot shown in Fig. 1.4. Here and in the following graphs the scales on the axes are enlarged for the sake of clarity relative to the default. For the same reason, the thickness of the lines is also somewhat greater than the original display. See the corresponding picture in Fig. 1.12.

0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5

−0.2

−0.6

−0.4

−0.8

−1 0 0.2 0.6 0.4 0.8 1

FIGURE 1.4 A MATLAB example of a simple x, y plot.

You can see that the result is normally in the form of a polygonal sequence.

This often leads to erroneous interpretations of graphs, especially when the abscissa values are far apart. Be careful. In addition, only numbers are placed on the axes automatically. You have to put in grids, axis labels, and titles yourself using the appropriate MATLAB commands.

The following commands generate the plot in Fig. 1.5. Here another line style (circles) has been chosen and the color has been changed to magenta (which cannot, of course, be shown here). (The default color in MATLAB is blue.)

>> t=(0:1:5);

>> s=sin(t);

>> plot(t,s,'k*')

0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5

−0.2

−0.4

−0.6

−0.8

−1 0 0.2 0.4 0.6 0.8 1

FIGURE 1.5 The x, y plot with a different “line style.”

In the next example a sine of amplitude 1 with frequency10 5 Hz, a cosine of amplitude 2 and frequency 3 Hz, and the exponential function e−2t are calculated for the time vector t=(0:0.01:2) and plotted:

>> t=(0:0.01:2);

>> sinfct=sin(2*pi*5*t);

>> cosfct=2*cos(2*pi*3*t);

>> expfct=exp(-2*t);

>> plot(t,[sinfct; cosfct; expfct])

This yields the graph shown in Fig. 1.6.

In Fig. 1.7 this graph is shown again, but using some of the possibilities for different line shapes in order to distinguish the plots of the functions from one another. The corresponding plot statement is

>> plot(t,sinfct,'k-', t, cosfct, 'b--', t, expfct, 'm.')

Here the variable t has to be repeated anew each time. The sine is plotted with the above settings, a black (black) solid curve (-), while the cosine is plotted in blue (blue) with a dashed curve (--), and the exponential function is in magenta (magenta) with a dotted curve (.).

10Note that the general form for a harmonic oscillation with frequency f , amplitude A, and phaseϕ is f (t) = A sin (2πft + ϕ).

0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2

−0.5

−1

−1.5

−2 0 0.5 1 1.5

FIGURE 1.6 x, y plot with multiple functions.

Besides these most frequently used plot functions, MATLAB also has a number of other two-dimensional plot functions. In signal processing the function stem is often used. It presents discrete signals in the form of a fence plot. This function, however, is only suitable for sparse data sets, for otherwise the lines come too close to one another and the small circles at the ends of

0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2

−0.5

−1

−1.5

−2 0 0.5 1 1.5 2

FIGURE 1.7 x, y plot with multiple functions and different line colors and styles.

0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2

−0.5

−1

−1.5

−2 0 0.5 1 1.5 2

FIGURE 1.8 x, y plot using the stem plot function.

the lines can overlap in an unsightly manner. In these cases plot is more intuitive. Fig. 1.8 shows the results of the following MATLAB sequence:

>> t=(0:0.05:2);

>> cosfct=2*cos(2*pi*t);

>> stem(t,cosfct)

>> box

One function that is specially suited to displaying time-discrete signals is the function stairs, which represents the signal in the form of a stair function.

Fig. 1.9 shows the result of the call

>> stairs(t,cosfct)

for the cosine signal defined above. A suitable labelling of the axes and a title line are also important for the documentation of graphs of this sort. In addition, it is often also necessary to provide a grid for the graph in order better to compare the values or to enlarge segments of a graph.

MATLAB, of course, has functions for this purpose. For the axis labels there are xlabel, ylabel, and title, for the grid there is the function grid, and for magnification there is the function zoom, which allows the enlargement of a segment with the mouse, as well as the command axis,

0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2

−0.5

−1

−1.5

−2 0 0.5 1 1.5 2

FIGURE 1.9 x, y plot using the stairs function.

for which the x and y ranges must be specified explicitly. Labels can be inserted inside the graph using the function text.

The graphs in Figs. 1.10 and 1.11 show the result of the following MATLAB command sequence, in which the above capabilities are used:

>> t=(0:0.05:2);

>> cosfct=2*cos(2*pi*t);

>> plot(t,cosfct)

>> xlabel('time / s')

>> ylabel('Amplitude / V')

>> text (0.75,0,'\leftarrow zero crossing','FontSize',18)

>> title('A cosine voltage with frequency 1 Hz')

>> figure % open a new window !

>> plot(t,cosfct)

>> xlabel('time / s')

>> ylabel('Amplitude / V')

>> grid % set grid frame

>> axis([0, 0.5, 0, 2]) % detail within interval [0, 0.5],

% but only amplitudes within

% the interval [0, 2]

>> title('Detail of the cosine voltage with frequency 1 Hz')

0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2

A cosine voltage with frequency 1 Hz

FIGURE 1.10 A labelled x, y plot using the plot function.

We shall not discuss the other two-dimensional plot functions at this point.

The reader can find out more about these possibilities in the help menu or in the book by Marchand11and experiment with them.

0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5

Detail of the cosine voltage with frequency 1 Hz

FIGURE 1.11 A segment of Fig. 1.10 using the ``axis'' command.

11P. Marchand, Graphics and GUIs with MATLAB, CRC Press, 1999.

In the following we shall, however, briefly discuss the possibilities for processing graphs, which are specially available during interactive operation.

Then three-dimensional graphs will be discussed.

Graphical Processing

MATLAB 7 has extensive improvements in the user interface compared to its predecessors (see Section 1.4). Thus, it offers some convenient possibilities for the processing and export of graphics in the interactive mode. Since this is of great importance for the documentation of MATLAB computations, we shall discuss it briefly at this point.

The plot window of a MATLAB graphic as seen by the user has the form shown in Fig. 1.12.

The essential functions for manipulation of graphics can be selected using the so-called toolbar located below the pull-down menus. These functions

FIGURE 1.12 The MATLAB plot window with a sample graph.

can, of course, also be reached through the pull-down menu itself. Besides the conventional Windows icons for save, print, etc., in the left-hand third of the toolbar, in the middle third of the toolbar you can see the magnifier symbol, with which a graphic can be enlarged or shrunk, as well as a symbol for rotating a graphic. The latter is especially practical for viewing three-dimensional graphics (see the next subsection) and is very useful. The icons in the right-hand third of the toolbar provide access to other useful functions, such as the so-called data cursor, with which the (x, y) coordinates of a point in the graph can be displayed by clicking on the given point. There is also a button with which the graphics can be provided interactively with a legend.

The show plot tools icon on the far right extends the plot window to a wider window with tools for graphical processing.

A detailed presentation of the possibilities at this point would go beyond the scope of this introduction. Instead, we shall illustrate the functionality with a small example.

If, for instance, you want to change the title label, select and click on the title text with the plot editing arrow and make your change. Similarly, by double clicking on the lines it is possible to change the line style. A double click on the axes makes it possible to change the axis scale and other properties of the axes. With a mouse click the plot window can be expanded at any time into a configuration window where the desired settings can be chosen. All the configuration possibilities can be obtained in a single view if, as mentioned above, you press the show plot tools icon. Fig. 1.13 shows the plot window when it is expanded in this way.

A selection of tools for manipulating a plot are also available. This is other-wise context dependent. Thus, the property editor - axes window is opened below when the intersection of the axes is clicked. If the function graph is clicked, then this window will be replaced by the corresponding property editorwindow.

Besides these, many more functions can be obtained through the menu items insert and tools, which make it possible to modify the appearance of a graphic afterward. This calls on the experimental playfulness of the reader.

Given the innumerable possibilities offered by the plot window for chang-ing graphics in MATLAB 7 in the interactive mode, the precedchang-ing discussion of the plot commands may seem to be of somewhat dubious utility for this purpose. In fact, processing plots with the tools in the plot window is simpler and more intuitive. Moreover, no commands have to be learned in combi-nation with their syntax. It has already been pointed out that MATLAB is a programming language (see Section 1.6). If you want to prepare completed

FIGURE 1.13 The plot-tools window.

graphics within a program, the above MATLAB commands provide the only way to do it.

Finally, the important functionalities for graphics export from MATLAB 7 should be mentioned at this point. In the plot window various formats, such as encapsulated postscript, TIFF, portable network graph-ics, etc., into which a graphic can be converted and saved, may be chosen using the menu command File - Save as .... Of course, the graph-ics can be exported into other applications via the Windows interface using Edit - Copy figurecommand.

Three-dimensional Plots

Here again, we shall not discuss all the capabilities of MATLAB in detail. The most important three-dimensional graphics functions are certainly mesh and surfsurffor the representation of a three-dimensional mesh or surface-mesh plot and contour for a contour plot. In the following example the two-dimensional function

f (x, y)= sin (x2+ y2)e−0.2·(x2+y2)

FIGURE 1.14 A three-dimensional plot using the mesh command.

is plotted using the function mesh or surf within the square [−3, 3] × [−3, 3] ,

which is provided with a rectangular grid with a step size (edge length) of 0.1. To do this the value of the function is calculated at every grid point. The value of the function is attached to a surface mesh (tile) and the entire graph is plotted in perspective with respect to a viewpoint specified by MATLAB (which, of course, can easily be changed using the methods described in the preceding section).

The following sequence of commands produces the plots shown in Figs. 1.14 and 1.15:

>> x=(-3:0.1:3); % grid frame in x direction

>> y=(-3:0.1:3)'; % grid frame in y direction

>> v=ones(length(x),1); % auxiliary vector

>> X=v*x; % grid matrix of the x values

>> Y=y*v'; % grid matrix of the y values

>> % function value

>> f=sin(X.^2+Y.^2).*exp(-0.2*(X.^2+Y.^2));

>> mesh(x,y,f) % mesh plot with mesh

>> mxf = max(max(f)); % maximum value of the function

>> mif = min(min(f)); % minimum value of the function

FIGURE 1.15 A three-dimensional plot using the surf command.

>> axis([-3,3,-3,3,mif,mxf])% adjust axes

>> xlabel('x-axis'); % label axes

>> ylabel('y-axis');

>> figure % new plot

>> surf(x,y,f) % surface mesh plot with surf

>> axis([-3,3,-3,3,mif,mxf])% adjust axes

>> xlabel('x-axis'); % label axes

>> ylabel('y-axis');

The technique for generating the x, y grid is of some interest. Here, elegant use has been made of matrix algebra, avoiding the need to write a double loop as would have to be done in the C++ programming language.

The reader should certainly take Problem 28 to heart in order to grasp what has actually been done and what the trick involves.

In order to compare the plot results from mesh and surf, the graph of Fig. 1.16 shows a three-dimensional contour plot of the function. It was generated using the following MATLAB commands:

>> contour3(x,y,f,30)

>> axis([-3,3,-3,3,mif,mxf]) % adjust axes

>> xlabel('x-axis'); % label axes

>> ylabel('y-axis');

The number 30 represents the number of contours to be plotted.

FIGURE 1.16 A three-dimensional plot using the contour3 command.

Subplots and Overlay Plots

Besides being able to plot graphs in different individual windows, MATLAB can also plot multiple (overlay) graphs in a single window. This can be done, for example, using the subplot command.

The following example shows how the magnitude and phase of the com-plex function f (t)= t2ejtjt can be plotted with the two plots one above the other:

>> t=(0:0.1:5);

>> f=(t.^2).*exp(j*t).*(j.^t); % * and ^ are field operations.

>> subplot(211) % plot the top graph

>> plot(t,abs(f))

>> subplot(212) % plot the bottom graph

>> plot(t,angle(f))

Fig. 1.17 shows the result.

Here we see that the command subplot only sets the axes of the graph in the right place. The plot, itself, is still provided by the plot command.

The parameters of the subplot command specify how many graphs are to be drawn altogether in the vertical (the first number) and horizontal (sec-ond number) directions. The third number specifies which of the subgraphs

0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 0

5 10 15 20 25

0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5

−4

−2 0 2 4

FIGURE 1.17 A graph with two plots using the subplot command.

is meant, going from upper left to lower right. For example subplot(325) signifies the fifth plot in an array of 3× 2 graphs (for the next plot command).

Another possibility for multiple plots in a single window is overlay graphs as shown in Figs. 1.6 and 1.7. Besides the ways described previously, multiple graphs can be plotted on top of one another using the hold command. This freezes the current graph so that the next graph is not plotted in its own window, but in the same window. Here is an example:

>> t = (0:0.5:10);

>> sinfct = sin(2*pi*5*t);

>> cosfct = 2*cos(2*pi*3*t);

>> plot(t,sinfct)

>> hold

>> plot(t,cosfct)

Here, the current graph is always the graph whose plot window is “on top,”

and, therefore, the last one processed. Before using the hold command, you have to make sure that the correct graph is being written over by clicking the corresponding window.

PROBLEMS

Work out the following problems to familiarize yourself with the plot functions.

NOTE Solutions to all problems can be found in Chapter 4.

Problem 23

Figure out why the sequence

>> t=(0:0.01:2);

>> sinfct=sin(2*pi*5*t);

>> cosfct=2*cos(2*pi*3*t);

>> expfct=exp(-2*t);

>> plot(t,[sinfct, cosfct, expfct])

leads to a MATLAB error.

Problem 24

Enter the MATLAB command sequence

>> t=(0:0.5:10);

>> sinfct=sin(2*pi*5*t);

>> cosfct=2*cos(2*pi*3*t);

>> expfct=exp(-2*t);

>> plot(t,[sinfct; cosfct; expfct])

and interpret the (somewhat odd) graphical result.

Problem 25

Experiment with the plot functions plot and stem using different dis-cretization step sizes and different line styles.

Vary the line style and axis partition using the editor command in the plot window.

Problem 26

Experiment with the plot functions semilogx, semilogy, and loglog, in order to become acquainted with the different possibilities for displaying logarithmic axes.

For this, use the frequency vector

ω = (0.01, 0.02, 0.03, 0.04, . . . , 5) rad/s,

which shows up in the so-called “transfer functions”12of an integrator, H(jω) = 1

jω and of a first order time delay element,

H(jω) = 1 1+ jω ,

which are encountered in signal processing and control engineering. Plot the magnitude of these functions.

Decide which display is best.

Problem 27

Label the plot results from Problem 26 using the appropriate MATLAB commands and experiment with the commands axis and zoom.

For comparison, work out the same problems using the editor commands in the plot window.

In addition, familiarize yourself with the documentation of a MATLAB graphic in a text processing program where you insert (paste) the graphic into a document using the interface Edit - copy figure.

Problem 28

Test the command sequence for the surf plot example in Section 1.2.5 with two vectors of the form

x =

−1 0 1

and y =

−2 0 2 and find the trick used to generate the x, y grid.

Problem 29

Check out some of the other three-dimensional plot functions using the example in Section 1.2.5. You can get a survey of these plot functions by typing in help graph3d in the MATLAB command interface.

Problem 30

Plot the magnitude and phase of the transfer functions used in Problem 26 as a overlay plot (to obtain a so-called Bode diagram). Use a logarithmic scale for the magnitude on the y axis.

12The concept of “transfer function” is discussed in the pertinent literature. An understanding of this concept is not essential for the problem under consideration.

Problem 31

Plot the exponential functions

e−t/2 and e−2t/5 over the interval[0, 2].

1. In a single overlay plot,

2. next to one another in different plots, and 3. one above the other in different plots.

Label one of the plots in a suitable fashion and then try to save this plot in an Microsoft Word file using the interface.

Problem 32

Calculate and plot the function

x2+ y2 on the rectangle[−2, 2] × [−1, 1].

For this, use a grid that has equidistant step sizes of 0.2 in the x direction and 0.1 in the y direction.

1.2.6 I/O Operations

I/O operations (Input/Output operations) relate to data transfer between MATLAB and external files. A mechanism of this sort is necessary if, for exam-ple, you want to import externally acquired data into MATLAB or transfer results from MATLAB to other applications.

The Load and Save Commands

MATLAB recognizes many file interfaces. The most elementary of these are represented by the load and save commands.

Thus, for example, with the command

>> save wsbackup

the content of the work space (i.e., that which is indicated by whos) will be saved in a binary file named wsbackup.mat (ending in .mat).

the content of the work space (i.e., that which is indicated by whos) will be saved in a binary file named wsbackup.mat (ending in .mat).