0% found this document useful (0 votes)
39 views12 pages

Matlab 5 Slide

Uploaded by

Yazan Z Awad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views12 pages

Matlab 5 Slide

Uploaded by

Yazan Z Awad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Lecture 8 Computer Applications 0933201 Chapter 5

UNIVERSITY OF JORDAN Nomenclature for a typical xy plot. Figure 5.1–1

Faculty of Eng. and Tech.


Electrical Engineering Dept.
Instructor: Ziad R. Al-Khatib

Introduction to MATLAB 7
for Engineers
William J. Palm III
Chapter 5
Advanced Plotting and Model Building

Z.R.K
Z.R.K
5-2 Z.R.K
More? See pages 260-261.

The autoscaling feature in MATLAB selects tick-mark


The following MATLAB session plots y 04 —18x spacing. Figure 5.1–2
for 0 d x d 52, where y represents the height of a
rocket after launch, in miles, and x is the
horizontal (downrange) distance in miles.
>>x = [0:0.1:52];
>>y = 0.4*sqrt(1.8*x);
>>plot(x,y)
>>xlabel(‘Distance (miles)’)
>>ylabel(‘Height (miles)’)
>>title(‘Rocket Height as a ...
Function of Downrange Distance’)

The resulting plot is shown on the next slide.


5-3 Z.R.K
5-4 Z.R.K

The plot will appear in the Figure window. You can


obtain a hard copy of the plot in several ways: When you have finished with the plot, close
the figure window by selecting Close from
1. Use the menu system. Select Print on the File
the File menu in the figure window.
menu in the Figure window. Answer OK when
you are prompted to continue the printing Note that using the Alt-Tab key combination
process. in Windows-based systems will return you
2. Type print at the command line. This to the Command window without closing
command sends the current plot directly to the the figure window.
printer. If you do not close the window, it will not
3. Save the plot to a file to be printed later or reappear when a new plot command is
imported into another application such as a executed. However, the figure will still be
word processor. You need to know something updated.
about graphics file formats to use this file
properly. See the subsection Exporting Figures.
5-5 Z.R.K
5-6 Z.R.K

Z.R.K. 2008 Page 1 of 12


Lecture 8 Computer Applications 0933201 Chapter 5

Requirements for a Correct Plot Requirements for a Correct Plot (continued)


The following list describes the essential features
of any plot: 3. If you are plotting more than one curve or
1. Each axis must be labeled with the name of the data set, label each on its plot or use a
quantity being plotted and its units! If two or legend to distinguish them.
more quantities having different units are 4. If you are preparing multiple plots of a
plotted (such as when plotting both speed and similar type or if the axis labels cannot
distance versus time), indicate the units in the convey enough information, use a title.
axis label if there is room, or in the legend or 5. If you are plotting measured data, plot
labels for each curve. each data point with a symbol such as a
2. Each axis should have regularly spaced tick circle, square, or cross (use the same
marks at convenient intervals—not too sparse, symbol for every point in the same data
but not too dense—with a spacing that is easy set). If there are many data points, plot
to interpret and interpolate. For example, use 0.1, them using the dot symbol.
0.2, and so on, rather than 0.13, 0.26, and so on.
5-7 Z.R.K
(continued …) 5-8 Z.R.K (continued …)

Requirements for a Correct Plot (continued) The grid and axis Commands
The grid command displays gridlines at the tick
6. Sometimes data symbols are connected by marks corresponding to the tick labels. Type grid
lines to help the viewer visualize the data, on to add gridlines; type grid off to stop
especially if there are few data points. plotting gridlines. When used by itself, grid
However, connecting the data points,
toggles this feature on or off, but you might want to
especially with a solid line, might be use grid on and grid off to be sure.
interpreted to imply knowledge of what occurs
You can use the axis command to override the
between the data points. Thus you should be
MATLAB selections for the axis limits. The basic
careful to prevent such misinterpretation. syntax is axis([xmin xmax ymin ymax]).
7. If you are plotting points generated by This command sets the scaling for the x- and y-axes
evaluating a function (as opposed to measured to the minimum and maximum values indicated.
data), do not use a symbol to plot the points. Note that, unlike an array, this command does not
Instead, be sure to generate many points, and
use commas to separate the values.
connect the points with solid lines.
5-9 Z.R.K
5-10 Z.R.K
More? See pages 264-265.

The effects of the axis and grid commands. Figure 5.1–3 The plot(y) function plots the values in y versus
the indices. Figure 5.1–4.
x = 0.1+0.9j; n = [0:0.01:10]; y = x.^n;
plot(y), xlabel(‘Real’), ylabel(‘Imaginary’)

5-11 Z.R.K
5-12 Z.R.K

Z.R.K. 2008 Page 2 of 12


Lecture 8 Computer Applications 0933201 Chapter 5
The function in Figure 5.1–5 generated with the plot
The fplot command plots a function specified
command, which gives more control than the fplot
as a string. Figure 5.1–5 command. Figure 5.1–6
>>f=‘cos(tan(x)) – tan(sin(x))’; fplot(f,[1 2]) >>x=[1:0.01:2]; y = cos(tan(x)) – tan(sin(x));
>>plot(x, y)

5-13 Z.R.K
5-14 Z.R.K

Plotting Polynomials with the An example of a Figure window. Figure 5.1–7

polyval Function.
To plot the polynomial
3x5 + 2x4 – 100x3 + 2x2 – 7x + 90
over the range –6 d x d 6 with a spacing
of 0.01, you type
>>x = [-6:0.01:6];
>>p = [3,2,-100,2,-7,90];
>>grid on
>>plot(x,polyval(p,x)), ...
xlabel(’x’), ylabel(’p’)
More? See page 268. 5-16
5-15 Z.R.K Z.R.K

Saving Figures Exporting Figures


To save the figure in a format that can be used by
To save a figure that can be opened in another application, such as the standard graphics
subsequent MATLAB sessions, save it in a file formats TIFF or EPS, perform these steps.
figure file with the .fig file name extension. 1. Select Export Setup from the File menu. This
dialog lets you specify options for the output file,
To do this, select Save from the Figure
such as the figure size, fonts, line size and style,
window File menu or click the Save button and output format.
(the disk icon) on the toolbar. 2. Select Export from the Export Setup dialog. A
standard Save As dialog appears.
If this is the first time you are saving the 3. Select the format from the list of formats in the
file, the Save As dialog box appears. Make Save As type menu. This selects the format of the
sure that the type is MATLAB Figure (*.fig). exported file and adds the standard file name
Specify the name you want assigned to the extension given to files of that type.
4. Enter the name you want to give the file, less the
figure file. Click OK.
extension. Then click Save.
5-17 Z.R.K
5-18 Z.R.K
More? See pages 270-271.

Z.R.K. 2008 Page 3 of 12


Lecture 8 Computer Applications 0933201 Chapter 5

Subplots
You can use the subplot command to obtain
On Windows systems, you can also copy several smaller “subplots” in the same figure.
a figure to the clipboard and then paste
The syntax is subplot(m,n,p). This
it into another application (like Paint):
command divides the Figure window into an
1. Select Copy Options from the Edit
array of rectangular panes with m rows and n
menu. The Copying Options page of the
Preferences dialog box appears. columns. The variable p tells MATLAB to place
the output of the plot command following the
2. Complete the fields on the Copying
subplot command into the pth pane.
Options page and click OK.
For example, subplot(3,2,5) creates an array
3. Select Copy Figure from the Edit menu.
of six panes, three panes deep and two panes
across, and directs the next plot to appear in
the fifth pane (in the bottom-left corner).
5-19 Z.R.K
5-20 Z.R.K

The following script file created Figure 5.2–1, Application of the subplot command. Figure 5.2–1

which shows the plots of the functions


y = e-1.2x sin(10x + 5) for 0 d x d 5 and
y _x3  100_ for 6 d x d 6.
x = [0:0.01:5];
y = exp(-1.2*x).*sin(10*x+5);
subplot(1,2,1)
plot(x,y),axis([0 5 -1 1])
x = [-6:0.01:6];
y = abs(x.^3-100);
subplot(1,2,2)
plot(x,y),axis([-6 6 0 350])
TheZ.R.K
figure is shown on the next slide.
5-21 5-22 Z.R.K
More on subplots? See page 271.

Data Markers and Line Types Data plotted using asterisks connected with a dotted line.
To plot y versus x with a solid line and u
versus v with a dashed line, type
plot(x,y,u,v,’--’), where the symbols
’--’ represent a dashed line. Table 5.2–1
gives the symbols for other line types.
To plot y versus x with asterisks (*) connected
with a dotted line, you must plot the data twice
by typing plot(x,y,’*’,x,y,’:’).
To plot y versus x with green asterisks ( )
connected with a red dashed line, you must
plot the data twice by typing
plot(x,y,’g*’,x,y,’r--’).
5-23 Z.R.K
5-24 Z.R.K

Z.R.K. 2008 Page 4 of 12


Lecture 8 Computer Applications 0933201 Chapter 5

Use of data markers. Figure 5.2–2

Specifiers for data markers,


line types, and colors. Table 5.2–1

Data markers† Line types Colors


Dot (.) . Solid line –– Black k
Asterisk (*) * Dashed line –– Blue b
Cross (u) u Dash-dotted –. Cyan c
Circle ( ) line Green g
Plus sign ()  Dotted line …. Magenta m
Square ( ) s Red r
Diamond ( ) d White w
Five-pointed star p Yellow y
(w)

†Other data markers are available. Search for “markers” in MATLAB

help.

5-25 Z.R.K
5-26 Z.R.K
More? See pages 273-274.

Application of the legend command. Figure 5.2–4


Labeling Curves and Data legend
The legend command automatically obtains from the
plot the line type used for each data set and displays a
sample of this line type in the legend box next to the string
you selected. The following script file produced the plot in
Figure 5.2–4.

x = [0:0.01:2];
y = sinh(x);
z = tanh(x);
plot(x,y,x,z,’--’),xlabel(’x’), ...
ylabel(’Hyperbolic Sine and ...
Tangent’),legend(’sinh(x)’,’tanh(x)’)

5-27 Z.R.K
5-28 Z.R.K

The gtext and text commands are also useful. Figure 5.2–5 Graphical solution of equations: Circuit representation of
a power supply and a load. Figure 5.2–6
i1 = 0.16 (e0.12v2 – 1)
R1 = 30 :, v1 = +15V. & v2 =(0 to 20)V

5-29 Z.R.K
See page 276. 5-30 Z.R.K

Z.R.K. 2008 Page 5 of 12


Lecture 8 Computer Applications 0933201 Chapter 5

Plot of the load line and the device curve for Application of the hold command. Figure 5.2–8
Previous circuit. Figure 5.2–7

5-31 Z.R.K
5-32 Z.R.K
See page 279.

Why use log scales? Rectilinear scales cannot properly display A loglog plot can display wide variations in data values.
variations over wide ranges. Figure 5.3–1 Figure 5.3–2
>> x=[0:.01:100]; y=sqrt((100*(1-0.01*x.^2).^2+0.02*x.^2)...
./ ((1-x.^2).^2+0.1*x.^2)); plot(x,y)

5-33 Z.R.K
5-34 Z.R.K
See page 282.

Logarithmic Plots Logarithmic Plots (continued)


It is important to remember the following 3. The tick-mark labels on a log scale are
points when using log scales: the actual values being plotted; they are
not the logarithms of the numbers.
1. You cannot plot negative numbers on a For example, the range of x values in the
log scale, because the logarithm of a plot in Figure 5.3–2 is from 10 001 to
negative number is not defined as a real 102 100.
number. 4. Gridlines and tick marks within a decade
2. You cannot plot the number 0 on a log are unevenly spaced. If 8 gridlines or tick
scale, because log10 0 = ln 0 = -f. marks occur within the decade, they
You must choose an appropriately small correspond to values equal to 2, 3, 4
number as the lower limit on the plot. 8, 9 times the value represented by the
first gridline or tick mark of the decade.
5-35 Z.R.K (continued…) 5-36 Z.R.K (continued…)

Z.R.K. 2008 Page 6 of 12


Lecture 8 Computer Applications 0933201 Chapter 5

Logarithmic Plots (continued) MATLAB has three commands for generating


plots having log scales. The appropriate
5. Equal distances on a log scale correspond to command depends on which axis must have
multiplication by the same constant (as a log scale.
opposed to addition of the same constant on a
rectilinear scale). 1. Use the loglog(x,y) command to
For example, all numbers that differ by a factor of have both scales logarithmic.
10 are separated by the same distance on a log
scale. That is, the distance between 0.3 and 3 2. Use the semilog x(x,y) command
is the same as the distance between 30 and
to have the x scale logarithmic and the y
300. This separation is referred to as a decade
scale rectilinear.
or cycle.
The plot shown in Figure 5.3–2 covers three
decades in x (from 0.01 to 100) and four
3. Use the semilog y(x,y) command
decades in y and is thus called a four-by-three- to have the y scale logarithmic and the x
cycle plot. scale rectilinear.
5-37 Z.R.K
5-38 Z.R.K

Two data sets plotted on four types of plots. Figure 5.3–3 Application of logarithmic plots: An RC circuit.
Figure 5.3–4

vo /vi = (1 / | 1 + RCs | )
s = jw, Xc = 1/jwC, Xc = 1/sC .

5-39 Z.R.K
See page 285. 5-40 Z.R.K

Frequency-response plot of a low-pass RC circuit. Frequency-response plot of a low-pass RC circuit.


Figure 5.3–5

5-41 Z.R.K
See pages 286-287. Z.R.K

Z.R.K. 2008 Page 7 of 12


Lecture 8 Computer Applications 0933201 Chapter 5
>> x = [0:pi/20:pi];
Specialized plot commands. Table 5.3–1 >> bar(x,sin(x))
Command Description

bar(x,y) Creates a bar chart of y versus x.

plotyy(x1,y1,x2,y2) Produces a plot with two y-axes, y1


on the left and y2 on the right.

polar(theta,r,’type’) Produces a polar plot from the polar


coordinates theta and r, using the
line type, data marker, and colors
specified in the string type.

stairs(x,y) Produces a stairs plot of y versus x.

stem(x,y) Produces a stem plot of y versus x.

5-43 Z.R.K
5-44 Z.R.K

>> x = [0:pi/50:2*pi]; >> x = [0:pi/20:2*pi];


>> polar(x, sin(2*x)),grid >> stairs(x,sin(x)),grid;
>> axis([0 2*pi -1 1]);

5-45 Z.R.K 5-46 Z.R.K

>> x = [-2*pi:pi/20:2*pi]; >> x = [-2*pi:pi/20:4*pi];


>> x = x + (~x)*eps; y=sin(pi*x)./(pi*x); >> fill(x,sin(x),'c');
>> stem(x,y), axis([-2*pi 2*pi -.25 1])
>> axis([0 4*pi -1 1])

5-47 Z.R.K 5-48 Z.R.K

Z.R.K. 2008 Page 8 of 12


Lecture 8 Computer Applications 0933201 Chapter 5

Interactive Plotting in MATLAB The interactive plotting environment


This interface can be advantageous in in MATLAB is a set of tools for:
situations where: x Creating different types of graphs,
x You need to create a large number of x Selecting variables to plot directly from
different types of plots, the Workspace Browser,
x You must construct plots involving many x Creating and editing subplots,
data sets,
x You want to add annotations such as
x Adding annotations such as lines,
rectangles and ellipses, or arrows, text, rectangles, and ellipses,
x You want to change plot characteristics and
such as tick spacing, fonts, x Editing properties of graphics objects,
bolding, italics, and colors. such as their color, line weight, and font.
More? See pages 292-298.
5-49 Z.R.K
5-50 Z.R.K

The Figure window with the Figure toolbar displayed. The Figure window with the Figure and Plot Edit toolbars displayed.
Figure 5.4–1 Figure 5.4–2

5-51 Z.R.K Z.R.K


5-52

The Figure window with the Plot Tools activated. Figure 5.4–3
The Plot Tools interface includes the following
three panels associated with a given figure.
x The Figure Palette: Use this to create and
arrange subplots, to view and plot workspace
variables, and to add annotations.
x The Plot Browser: Use this to select and
control the visibility of the axes or graphics
objects plotted in the figure, and to add data
for plotting.
x The Property Editor: Use this to set basic
properties of the selected object and to obtain
access to all properties through the Property
Inspector.

5-53 Z.R.K
5-54 Z.R.K

Z.R.K. 2008 Page 9 of 12


Lecture 8 Computer Applications 0933201 Chapter 5

The polyfit function is based on the Three-Dimensional Line Plots plot3


least-squares method. Its syntax is
The curve x = e-0.05t sin t, y = e-0.05t cos t,
p = Fits a polynomial of degree
polyfit(x,y,n)
z = t can be plotted with the
n to data described by the
vectors x and y, where x is plot3(x , y, z) function.
the independent The following program uses the plot3 function
variable. Returns a row to generate the 3-D spiral curve shown in Figure 5.8–1.
vector p of length n+1 that
>>t = [0:pi/50:10*pi];
contains the polynomial
>>plot3(exp(-0.05*t).*sin(t),...
coefficients in order of
exp(-0.05*t).*cos(t),t),...
descending powers.
xlabel(’x’),ylabel(’y’),zlabel(’z’),grid

5-55 Z.R.K See page 315, Table 5.6-1. 5-56 Z.R.K

The curve x = e-0.05t sin t, y = e-0.05t cos t, z = t plotted with


the plot3(x , y, z) function. Figure 5.8–1 Surface Plots mesh:
The following session shows how to generate
the surface plot of the function
22 2
z = xe-[(x-y ) +y ], for 2 d x d 2 and 2 d y d 2,
with a spacing of 0.1. This plot appears in Figure
5.8–2.

>>[X,Y] = meshgrid(-2:0.1:2);
>>Z = X.*exp(-((X-Y.^2).^2+Y.^2));
>>mesh(X,Y,Z),xlabel(’x’), ...
ylabel(’y’), zlabel(’z’)

5-57 Z.R.K
More? See pages 334-335. 5-58 Z.R.K
See the next slide.

22 2
A plot of the surface z = xe-[(x-y ) +y ]
created with the mesh function. Figure 5.8–2 The following session generates the contour
plot of the function whose surface plot is shown
2)2+y2]
in Figure 5.8–2; namely, z = xe-[(x-y ,
for 2 d x d 2 and 2 d y d 2, with a spacing
of 0.01. This plot appears in Figure 5.8–3.

>>[X,Y] = meshgrid(-2:0.1:2);
>>Z = X.*exp(-((X- Y.^2).^2+Y.^2));
>>contour(X,Y,Z),xlabel(’x’),ylabel(’y’)

5-59 Z.R.K
More? See pages 335-336. 5-60 Z.R.K

Z.R.K. 2008 Page 10 of 12


Lecture 8 Computer Applications 0933201 Chapter 5
22 2
A contour plot of the surface z = xe-[(x-y ) +y ] created
Three-dimensional plotting functions. Table 5.8–1
with the contour function. Figure 5.8–3
Function Description

contour(x,y,z) Creates a contour plot.


mesh(x,y,z) Creates a 3D mesh surface plot.
meshc(x,y,z) Same as mesh but draws contours under the
surface.
meshz(x,y,z) Same as mesh but draws vertical reference lines
under the surface.
surf(x,y,z) Creates a shaded 3D mesh surface plot.
surfc(x,y,z) Same as surf but draws contours under the
surface.
[X,Y] = meshgrid(x,y) Creates the matrices X and Y from the vectors x
and y to define a rectangular grid.
[X,Y] = meshgrid(x) Same as [X,Y]= meshgrid(x,x).
waterfall(x,y,z) Same as mesh but draws mesh lines in one
direction only.

5-61 Z.R.K
More? See page 337. 5-62 Z.R.K

2 2
Plots of the surface z = xe-(x +y ) created with the mesh Example to plot 3D
function and its variant forms: a) mesh, b) meshc,
c) meshz, and d) waterfall. Figure 5.8–4 If you want to see the famous Mexican
hat , type the following commands :
>> [x y] = meshgrid(-8:0.5:8);
>> r = sqrt(x.ˆ2 + y.ˆ2) + eps;
>> z = sin(r)./r;
>> mesh(z);
Why + eps ?
Try surf(z) to generate a faceted (tiled)
view of the surface.
Then try with surf(z) the shading
interp command.
5-63 Z.R.K 5-64 Z.R.K

Famous Mexican hat, with


5-65 Famous Mexican hat.
Z.R.K 5-66 meshgrid(-8:0.1:8) and surf(z)
Z.R.K

Z.R.K. 2008 Page 11 of 12


Lecture 8 Computer Applications 0933201 Chapter 5

Visualizing vector fields


The function quiver draws little arrows to indicate a
gradient or other vector field. Although it produces a 2-D
plot, it’s often used in conjunction with contour. As an
example, consider the scalar function of two variables
V = x2 + y. The gradient of V is defined as the vector field
ೢV = ( ˜V / ˜x , ˜V / ˜y ) = (2x, 1).
The following statements draw arrows indicating the
direction of ೢV at points in the x-y plane (see the next figure).
[x y] = meshgrid(-2:.2:2, -2:.2:2);
V = x.^2 + y;
dx = 2*x;
dy = dx; % dy same size as dx
dy(:,:) = 1; % now dy is same size as dx but all 1’s
contour(x, y, V), hold on
Famous Mexican hat, with quiver(x, y, dx, dy), hold off
5-67 meshgrid(-8:0.1:8), surf(z)
Z.R.K and shading interp. 5-68 Z.R.K

Gradients and level surfaces Example to plot 3D with surface and colormap:
See Primer in Matlab

figure(1) ; clf
t = linspace(0, 2*pi, 512);
[u,v] = meshgrid(t) ;
a = -0.2 ; b = .5 ; c = .1 ;
n = 2;
x = (a*(1-v/(2*pi)) .* (1+cos(u)) + c) .* cos(n*v);
y = (a*(1-v/(2*pi)) .* (1+cos(u)) + c) .* sin(n*v);
z = b*v/(2*pi) + a*(1-v/(2*pi)) .* sin(u);
surf(x,y,z,y)
shading interp
axis off
axis equal
colormap(hsv(1024))
material shiny
lighting gouraud
lightangle(80, -40)
lightangle(-90, 60)
view([-150 10])
Z.R.K Z.R.K
5-70

End of Chapter 5

Problems Page 340 - 357 !


Solve: 3, 9, 11, 27, 35, 49, 52.
www.ju.edu.jo\zkhatib
5-71 Z.R.K
Z.R.J.K
Z.R.K

Z.R.K. 2008 Page 12 of 12

You might also like