4.plot two and three-dimensional...

16
25 4.Plot Two and Three-Dimensional Graphics The MATLAB environment provides a wide variety of techniques to display data graphically. The plot function has different forms, depending on the input arguments. If y is a vector, plot(y) produces a piecewise linear graph of the elements of y versus the index of the elements of y. If you specify two vectors as arguments, plot(x,y) produces a graph of y versus x. 4.1 Two-Dimensional Graphics Suppose you want to graph the function y = x 3 over the x domain −1 to 1. The first step is to generate the data to plot. It is simple to evaluate a function like this because the MATLAB software can distribute arithmetic operations over all elements of a multivalued variable. For example, the following statement creates a variable x that contains values ranging from -1 to 1 in increments of 0.1 (you could also use the linspace function to generate data for x). The second statement raises each value in x to the third power and stores these values in y: x = -1:.1:1; % Define the range of x y = x.^3; % Raise each element in x to the third power plot(x,y) 4.2 Changing the Appearance of Lines and Markers You can specify your own colors, markers, and line styles by giving plot an extra argument. This optional additional argument is a character string consisting of one or more characters from the following table

Upload: others

Post on 13-Apr-2021

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 4.Plot Two and Three-Dimensional Graphicsfmusaly.kau.edu.sa/Files/0000823/Files/101561_Chapter4.pdf · 2013. 9. 28. · 4.3 Three-Dimensional Graphics Matlab provides a variety of

25

4.Plot Two and Three-Dimensional Graphics

The MATLAB environment provides a wide variety of techniques to display datagraphically. The plot function has different forms, depending on the input arguments. If yis a vector, plot(y) produces a piecewise linear graph of the elements of y versus theindex of the elements of y. If you specify two vectors as arguments, plot(x,y) produces agraph of y versus x.

4.1 Two-Dimensional Graphics

Suppose you want to graph the function y = x3 over the x domain −1 to 1. The first stepis to generate the data to plot.

It is simple to evaluate a function like this because the MATLAB software can distributearithmetic operations over all elements of a multivalued variable.

For example, the following statement creates a variable x that contains values rangingfrom -1 to 1 in increments of 0.1 (you could also use the linspace function to generatedata for x). The second statement raises each value in x to the third power and storesthese values in y:

x = -1:.1:1; % Define the range of xy = x.^3; % Raise each element in x to the third powerplot(x,y)

4.2 Changing the Appearance of Lines and Markers

You can specify your own colors, markers, and line styles by giving plot an extraargument. This optional additional argument is a character string consisting of oneor more characters from the following table

Page 2: 4.Plot Two and Three-Dimensional Graphicsfmusaly.kau.edu.sa/Files/0000823/Files/101561_Chapter4.pdf · 2013. 9. 28. · 4.3 Three-Dimensional Graphics Matlab provides a variety of

26

Symbol Color Symbol Marker Symbol Line styleB blue . point - solid lineG green O circle : dotted linR red X x-mark -. dash-dot lineC cyan + plus -- dashed lineM magenta * starY yellow S squareK black D diamondW white ^ triangle

< triangle left> triangle rightP pentagramH hexagram

Try

x=-2:0.1:2; f=2*x.^2-1; g=3*x.^3+1; plot(x,f,':',x,g,'r')

To add a title and axis labels write:

xlabel('variable x')ylabel('functions f & g')title('Example')legt = str2mat('f','g');legend(legt,0)

For example to add a legend to a graph showing a sine and cosine function

x = -pi:pi/20:pi;f1 = sin(x);f2 = cos(x);plot(x,f1,'-ro',x,f2,'-.b')h = legend('sin','cos',2);

Page 3: 4.Plot Two and Three-Dimensional Graphicsfmusaly.kau.edu.sa/Files/0000823/Files/101561_Chapter4.pdf · 2013. 9. 28. · 4.3 Three-Dimensional Graphics Matlab provides a variety of

27

fplot

Plot a function between specified limits. The function must be of the form = ( ),where is a vector whose range specifies the limits, and is a vector the same size asand contains the function's value at the points in . For example to plot tanh , for ∈[−2,2], use the following command:

fplot('tanh',[-2 2])

Try : fplot('x^2',[-2 2])

subplot

subplot divides the current figure into rectangular panes that are numbered rowwise. Eachpane contains an axes object. Subsequent plots are output to the current pane.

h = subplot(m,n,p) or subplot(mnp) breaks the figure window into an m-by-nmatrix of small axes, selects the pth axes object for the current plot, and returns the axeshandle. The axes are counted along the top row of the figure window, then the secondrow, etc. For example,

Page 4: 4.Plot Two and Three-Dimensional Graphicsfmusaly.kau.edu.sa/Files/0000823/Files/101561_Chapter4.pdf · 2013. 9. 28. · 4.3 Three-Dimensional Graphics Matlab provides a variety of

28

x=-5:0.2:5;f=x.^2;g=x.^3;subplot(2,1,1); plot(f)subplot(2,1,2); plot(g)

The following illustration shows four subplot regions and indicates the command used tocreate each.

Page 5: 4.Plot Two and Three-Dimensional Graphicsfmusaly.kau.edu.sa/Files/0000823/Files/101561_Chapter4.pdf · 2013. 9. 28. · 4.3 Three-Dimensional Graphics Matlab provides a variety of

29

To get the following combinations produce asymmetrical arrangements of subplots go tohelp subplot.

Page 6: 4.Plot Two and Three-Dimensional Graphicsfmusaly.kau.edu.sa/Files/0000823/Files/101561_Chapter4.pdf · 2013. 9. 28. · 4.3 Three-Dimensional Graphics Matlab provides a variety of

30

Plot polar coordinates

The polar function accepts polar coordinates, plots them in a Cartesian plane, and drawsthe polar grid on the plane.

polar(theta,rho) creates a polar coordinate plot of the angle theta versus the radiusrho. theta is the angle from the x-axis to the radius vector specified in radians; rho is thelength of the radius vector specified in dataspace units.

Here an examples creating a simple polar plot using a dashed red line:

t = 0:.01:2*pi; polar(t,sin(2*t).*cos(2*t),’r’)

A second example is

t = 0:pi/20:2*pi;plot(sin(t),2*cos(t))grid on

The command axis square makes the x- and y-axes equal in length. If you want the x-and y-data units to be equal, use the command axis equal. If you want the axes shapeto conform to the plotted data, use the tight option in conjunction with equal. axisequal tight.

Page 7: 4.Plot Two and Three-Dimensional Graphicsfmusaly.kau.edu.sa/Files/0000823/Files/101561_Chapter4.pdf · 2013. 9. 28. · 4.3 Three-Dimensional Graphics Matlab provides a variety of

31

The table below shows all available MATLAB 2-D plot functions. If you are reading thisonline, you can click any icon to see the documentation for that function. Techniques forusing many of the functions are also discussed in later sections of this document.

Page 8: 4.Plot Two and Three-Dimensional Graphicsfmusaly.kau.edu.sa/Files/0000823/Files/101561_Chapter4.pdf · 2013. 9. 28. · 4.3 Three-Dimensional Graphics Matlab provides a variety of

32

4.3 Three-Dimensional Graphics

Matlab provides a variety of functions to display three-dimensional data. Some functionsplot lines in three dimensions, while others draw surfaces.

Line plotes

The plot3 function displays a three-dimensional plot of a set of data points. The generalform is

plot3(x1,y1,z1,x2,y2,z2,…,xn,yn,zn).Where xn,yn and zn are vectors or matrices.

Here is an example of a three-dimensional helix:

t = 0:pi/50:10*pi;

plot3(sin(t), cos(t), t)

grid on, axis square

Figure ToolBarsThe figure's default toolbar provides shortcuts to commonly used features. The followingpicture shows the features available from this toolbar.

Note that you can enable two other toolbars from the View menu

Page 9: 4.Plot Two and Three-Dimensional Graphicsfmusaly.kau.edu.sa/Files/0000823/Files/101561_Chapter4.pdf · 2013. 9. 28. · 4.3 Three-Dimensional Graphics Matlab provides a variety of

33

Mesh and Surface Plot

Matlab defines a mesh surface by the z-coordinates of points above a rectangular grid inthe xy-plane. The result looks like a fishing net.

The first step in generating the mesh plot of a function of two variables, ),,( yxfz is togenerate X and Y matrices consisting of repeated rows and columns, respectively, oversome range of x and y. Matlab provides the function meshgrid

[X,Y] = meshgrid(x,y)

transforms the domain specified by vectors x and y into arrays X and Y, which can beused to evaluate functions of two variables and three-dimensional mesh/surface plots.The rows of the output array X are copies of the vector x; columns of the output array Yare copies of the vector y.

Here is an example:

[X,Y] = meshgrid(-2:.2:2);

R = sqrt(X + Y.^2);

Z = cos(R);

mesh(X,Y,Z)

A surface plot looks like the mesh plot, except that the spaces between the lines (calledpatches) are filled in. an example is:surf(Z) or surf(X,Y,Z)

Other three-dimensional plotting are:

ribbon(x,y) which is the same as plot(x,y), except, that the columns of y are plotted asseparated ribbons in three dimensions. Here is an examplex=linspace(0.2*pi,6); y=sin(x); ribbon(x,y)

see: contour, contourf, surfc, meshc , meshz and surfl.

Page 10: 4.Plot Two and Three-Dimensional Graphicsfmusaly.kau.edu.sa/Files/0000823/Files/101561_Chapter4.pdf · 2013. 9. 28. · 4.3 Three-Dimensional Graphics Matlab provides a variety of

34

4.4 polynomials Curve Fitting and Interpolation

In Matlab polynomial is represented by row vector of its coefficients in descending order.For example − 12 + 25 + 16 is entered as

P = [1 -12 0 25 16]P =

1 -12 0 25 16

r = roots(P)r =

11.81111.8218

-0.8165 + 0.2774i-0.8165 - 0.2774i

>> q = poly(r)q =

1 -12 0 25 16

>> v = polyval(P,2)v =-14

polyfit finds the coefficients of a polynomial that fits a set of data in a least-squaressense.

p = polyfit(x,y,n)

x and y are vectors containing the x and y data to be fitted, and n is the order of thepolynomial to return. For example, consider the x-y test data

x = [1 2 3 4 5]; y = [5.5 43.1 128 290.7 498.4];

A third order polynomial that approximately fits the data is

p = polyfit(x,y,3)x2 = 1:.1:5;y2 = polyval(p,x2);plot(x,y,'o',x2,y2)grid on

1 1.5 2 2.5 3 3.5 4 4.5 50

50

100

150

200

250

300

350

400

450

500

Page 11: 4.Plot Two and Three-Dimensional Graphicsfmusaly.kau.edu.sa/Files/0000823/Files/101561_Chapter4.pdf · 2013. 9. 28. · 4.3 Three-Dimensional Graphics Matlab provides a variety of

35

Try

x = (0: 0.1: 2.5);y = erf(x);p = polyfit(x,y,6)x = (0: 0.1: 5);y = erf(x);f = polyval(p,x);plot(x,y,'.r',x,f,'-')axis([0 5 0 2])

The table below shows all available MATLAB 3-D and volumetric plot functions. Itincludes functions that generate 3-D data (cylinder, ellipsoid, sphere), but most plot eitherarrays of data or functions. If you are reading this online, you can click any picture in thetable to see the documentation for that function.

Page 12: 4.Plot Two and Three-Dimensional Graphicsfmusaly.kau.edu.sa/Files/0000823/Files/101561_Chapter4.pdf · 2013. 9. 28. · 4.3 Three-Dimensional Graphics Matlab provides a variety of

36

For information about and examples of using 3-D plotting functions, see “Creating 3-DGraphs” in the 3-D Visualization documentation.

Example 3-D Stem Plot of an FFT

Fast Fourier transforms are calculated at points around the unit circle on the complexplane. It is interesting to visualize the plot around the unit circle.

Calculating the unit circle:

th = (0:127)/128*2*pi;

x = cos(th); y = sin(th);

and the magnitude frequency response of a step function. The command

f = abs(fft(ones(10,1),128));

displays the data using a 3-D stem plot, terminating the stems with filled diamondmarkers:

stem3(x,y,f','d','fill')

view([-65 30])

Label the graph with the statements

Page 13: 4.Plot Two and Three-Dimensional Graphicsfmusaly.kau.edu.sa/Files/0000823/Files/101561_Chapter4.pdf · 2013. 9. 28. · 4.3 Three-Dimensional Graphics Matlab provides a variety of

37

xlabel('Real')

ylabel('Imaginary')

zlabel('Amplitude')

title('Magnitude Frequency Response')

To change the orientation of the view, turn on mouse-based 3-D rotation:

rotate3d on

Example Combining Stem and Line Plots

Three-dimensional stem plots work well for visualizing discrete functions that do notoutput a large number of data points. For example, use stem3 to visualize the Laplacetransform basis function, y=e-st, for a particular constant value of s:

t = 0:.1:10; % Time limits

s = 0.1+i; % Spiral rate

y = exp(-s*t); % Compute decaying exponential

Using t as magnitudes that increase with time, create a spiral with increasing height anddraw a curve through the tops of the stems to improve definition:

-1

-0.5

0

0.51

-1-0.5

00.5

10

2

4

6

8

10

Real

Magnitude Frequency Response

Imaginary

Am

plitu

de

Page 14: 4.Plot Two and Three-Dimensional Graphicsfmusaly.kau.edu.sa/Files/0000823/Files/101561_Chapter4.pdf · 2013. 9. 28. · 4.3 Three-Dimensional Graphics Matlab provides a variety of

38

stem3(real(y),imag(y),t)

hold on

plot3(real(y),imag(y),t,'r')

hold off

view(-39.5,62)

Label the GraphAdd axes labels with the statements

xlabel('Real')

ylabel('Imaginary')

zlabel('Magnitude')

This type of plot is useful for drawing time-history plots of digitally sampled datasystems.

-1

-0.50

0.5

1

-1

-0.5

0

0.5

10

5

10

RealImaginary

Mag

nitu

de

Page 15: 4.Plot Two and Three-Dimensional Graphicsfmusaly.kau.edu.sa/Files/0000823/Files/101561_Chapter4.pdf · 2013. 9. 28. · 4.3 Three-Dimensional Graphics Matlab provides a variety of

39

Exercises

1. In a single figure plot the two functions = , = √ + 2, 0 ≤ ≤ 10, Showas a solid red line, and as a dotted green line. Write a title Example Plot.

2. Plot = sin( ) , 0 ≤ ≤ 5.3. Plot:

a) ( , ) = sin( ) , , ∈ [−2,2].b) = sin( ), = cos( ) sin( ), = sin( ), , ∈ [− , ] .

4. Plot each of the following functions in the indicated domain:

i) = ( )( ) 0 ≤ ≤ 2ii) = ( ) , 0 ≤ ≤ 4iii) = , 0 ≤ ≤ 5

a) separately.b) all functions in a single figure. Indicate the meaning of each curve by legends.

5. Plot the following function by a smooth curve in the range, 0 ≤ ≤ 2( ) = sin , ≤3 sin , >6. Plot the parametric curve ( ) = (sin(5 ), sin(3 )) fot 0 ≤ ≤ 2 .

7. Plot the parametric curve = (2 + cos(24 )) cos = (2 + cos(24 )) sin , =sin(24 ), for 0 ≤ ≤ 28. Plot the parametric surface = (2 + cos( )) cos = (2 + cos( )) sin ,= sin( ), for 0 ≤ ≤ 2 and 0 ≤ ≤ 29. Find a polynomial of degree 4 that fits the data, then find an approximation of(0.35).

0.1 0.2 0.4 0.5 0.6 0.7

1.1052 1.2214 1.4918 1.6487 1.8221 2.0138

Page 16: 4.Plot Two and Three-Dimensional Graphicsfmusaly.kau.edu.sa/Files/0000823/Files/101561_Chapter4.pdf · 2013. 9. 28. · 4.3 Three-Dimensional Graphics Matlab provides a variety of

40

10. Fit the following data set by a quadratic polynomial:

x = [0.1, 0.4, 0.5, 0.7, 0.9]; y = [0.61, 0.92, 0.99, 1.52, 2.03];

and plot both data set and the fitted curve.

11. Find the roots of the polynomial ( ) = − 6 + 10 − 11 + 6, and evaluate(3.5).12. Describe the command plotyy and give an example.

13. What do you know about Pie Charts? Give examples.