an engineer’s guide to matlab 3rd edition chapter 6 2d graphics
DESCRIPTION
AN ENGINEER’S GUIDE TO MATLAB 3rd Edition CHAPTER 6 2D GRAPHICS. Chapter 6 – Objective Present the implementation of a wide selection of two-dimensional plotting capabilities. Topics. Introduction: Graphics Management Basic 2D Plotting Commands Changing a Graph’s Overall Appearance - PowerPoint PPT PresentationTRANSCRIPT
Copyright © Edward B. Magrab 2009
Chapter 6
1
An Engineer’s Guide to MATLAB
AN ENGINEER’S GUIDE TO MATLAB
3rd Edition
CHAPTER 6
2D GRAPHICS
Copyright © Edward B. Magrab 2009
Chapter 6
2
An Engineer’s Guide to MATLAB
Chapter 6 – Objective
• Present the implementation of a wide selection of two-dimensional plotting capabilities.
Copyright © Edward B. Magrab 2009
Chapter 6
3
An Engineer’s Guide to MATLAB
Topics
Introduction: Graphics Management
Basic 2D Plotting Commands
Changing a Graph’s Overall Appearance
Special Purpose Graphs
Reading, Displaying, and Manipulating Digital Images
Copyright © Edward B. Magrab 2009
Chapter 6
4
An Engineer’s Guide to MATLAB
Graph Annotations and Enhancement
• Introduction
• Axes and Curve Labels, Figure Titles, Legends, and Text
• Filling in Regions
• Greek Letters, Mathematical Symbols, Subscripts, and Superscripts
• Altering the Attributes of Axes, Curves, and Text
• Positioning One Figure Inside Another Figure
• Interactive Plotting
• Animation
Topics
Copyright © Edward B. Magrab 2009
Chapter 6
5
An Engineer’s Guide to MATLAB
Introduction –
MATLAB provides a wide selection of very flexible and easy-to-implement two- and three-dimensional plotting capabilities.
The plotting functions can be grouped into three categories:
• graphics management
• curve and surface generation
• annotation and graph characteristics
Although there are quite a few plotting functions, for the most part their syntax is similar and they can be annotated with the same set of functions.
Copyright © Edward B. Magrab 2009
Chapter 6
6
An Engineer’s Guide to MATLAB
Purpose of a Graphic*
A graph should communicate complex ideas with clarity, precision, and efficiency.
Graphical excellence is attained when the viewer obtains the greatest number of ideas in the shortest time with the least amount of ink.
* E. Tufte, Visual Display of Quantitative information, Graphics Press, Cheshire, CT, 1997
Copyright © Edward B. Magrab 2009
Chapter 6
7
An Engineer’s Guide to MATLAB
The Functions Whose Usage We Shall Illustrate Are - Management Generation Annotation and
Characteristics
figure hold subplot zoom
3D rotate3d view
2D axes bar convhull delauney fill image loglog movie patch pie plot plotyy polar semilogx semilogy stairs stem voronoi
3D contour, contour3, contourf
cylinder mesh, meshc, meshz
pie3 plot3 surf, surfc waterfall
2D and 3D axis, axis equal, axis off, axis image box clabel grid legend set text title xlabel xlim ylabel ylim
3D colorbar colormap shading text3 zlabel
Copyright © Edward B. Magrab 2009
Chapter 6
8
An Engineer’s Guide to MATLAB
When generating graphed entities one should expend the effort so that each figure –
• Meets the solution’s objective by illustrating what is important and significant.
• Exhibits clarity and specificity by being fully annotated with the –
Axes labeled Figure titled Curves identified (if more than one) Important numerical values displayed
However, any devices that are used to enhance the figure, such as color, line type, symbols, and text should do so without being distracting.
Copyright © Edward B. Magrab 2009
Chapter 6
9
An Engineer’s Guide to MATLAB
• A typical set of graph-creating expressions consists of management functions, followed by one or more graph-generation functions, and followed in turn by annotation functions, which may be followed by additional management functions.
• Except for the management functions, the order of these functions is, in most applications, arbitrary.
• The employment of the annotation and graph characteristic functions is optional.
• MATLAB scales the axes and labels the axes’ magnitudes, even if more than one set of data is plotted.
Thus, one can always obtain a partially annotated graph, provided that the function’s syntax has been used correctly.
Copyright © Edward B. Magrab 2009
Chapter 6
10
An Engineer’s Guide to MATLAB
• A graph is created in a figure window, which is a window created by MATLAB at execution time, when any one of its graph management, generation, or annotation and characteristics functions is invoked.
• When a script or function uses more than one graph-generation function MATLAB creates a new figure window.
• Any previously created window is removed prior to creating the new figure window.
• To retain each new graph in its own figure window, one must use
figure(n)
where n is an integer.
If the argument of figure is omitted, then MATLAB gives it the next integer value.
Copyright © Edward B. Magrab 2009
Chapter 6
11
An Engineer’s Guide to MATLAB
• One can also place several independently created graphs in one figure window with
subplot(i, j, k)
where
i, j divide the window into sectors (rows and columns)
k indicates in which sector a graph is to be placed
A value of 1 for this argument indicates the upper left corner, and the product of the number of rows and columns indicates the lower right corner.
As the numbers increase, they indicate the sectors from left to right, starting at the top row.
Copyright © Edward B. Magrab 2009
Chapter 6
12
An Engineer’s Guide to MATLAB
• Any annotation and management functions that appear in the program after figure and/or subplot apply only to that sector indicated by the third argument of subplot.
• Within each sector, any compatible set of the 2D or 3D graph generation functions can be used.
Copyright © Edward B. Magrab 2009
Chapter 6
13
An Engineer’s Guide to MATLAB
Examples –
Script or Functionfigure(1)plotting expressions
Script or Function figure(2)subplot(1, 2, 1)plotting expressionssubplot(1, 2, 2)plotting expressions
Copyright © Edward B. Magrab 2009
Chapter 6
14
An Engineer’s Guide to MATLAB
Script or Functionfigure(3)subplot(2, 1, 1)plotting expressionssubplot(2, 1, 2)plotting expressions
Script or Functionfigure(4)subplot(2, 3, 3)plotting expressionssubplot(2, 3, 2)plotting expressionssubplot(2, 3, 1)plotting expressionssubplot(2, 3, 4)plotting expressionssubplot(2, 3, 5)plotting expressionssubplot(2, 3, 6)plotting expressions
Copyright © Edward B. Magrab 2009
Chapter 6
15
An Engineer’s Guide to MATLAB
• Since each graph-generation function creates a new figure window, in order to draw more than one curve, surface, or line (or combination of these) on a given graph, one must use
hold on
which holds the current window (or subplot sector) active.
• All figures that have been created can be copied to the Windows clipboard by selecting Copy Figure from the Edit pull-down menu within each figure’s window.
This figure can then be transferred (pasted) to a page in a word processor program and will be in the Windows metafile format.
Copyright © Edward B. Magrab 2009
Chapter 6
16
An Engineer’s Guide to MATLAB
Copyright © Edward B. Magrab 2009
Chapter 6
17
An Engineer’s Guide to MATLAB
Figure Format Conversion –
MATLAB provides the means to convert a figure to a format compatible with many common print devices.
For example, if one wants to save the graphics appearing in the active figure window as –
A level-2 encapsulated postscript file for black-and-white printers,
With the name FileName.eps,
Such that a “tiff” preview image of the figure can be displayed in a Word document,
then one uses
Copyright © Edward B. Magrab 2009
Chapter 6
18
An Engineer’s Guide to MATLAB
print('-deps2', '-tiff', 'c:\path\FileName.eps')
where
-tiff is a keyword indicating that a tiff preview is available.
-deps2 is a keyword to indicate that a level-2 encapsulated postscript file is to be created.
path describes the directory and subdirectory names where the file will reside.
Copyright © Edward B. Magrab 2009
Chapter 6
19
An Engineer’s Guide to MATLAB
Basic 2D Plotting Commands
The basic 2D plotting command is
plot(u, v, c)
where
u and v are the x and y coordinates, respectively, of a point or a series of points.
These points are either a pair of numbers, vectors of the same length, matrices of the same order, or expressions that, when evaluated, result in one of these three quantities.
Copyright © Edward B. Magrab 2009
Chapter 6
20
An Engineer’s Guide to MATLAB
The quantity c is a string of characters.
One character specifies the line/point color.
One character specifies the point type, if points are to be plotted.
One or two characters are used to specify the line characteristics.
The order of the three sets of characters within the single quotes is not important.
If c is omitted, then the system’s default values are used.
If more than one curve is drawn, then the line colors change according to the default sequence.
Copyright © Edward B. Magrab 2009
Chapter 6
21
An Engineer’s Guide to MATLAB
When both lines and points are to be plotted, but the points defining the line (u1, v1) are different from the points that are to be plotted (u2, v2), we use either
plot(u1, v1, c1, u2, v2, c2)
or
plot(u1, v1, c1)hold onplot(u2, v2, c2)
where
c1 contains the symbols for the line type and color.
c2 contains the symbols for the point type and color.
Copyright © Edward B. Magrab 2009
Chapter 6
22
An Engineer’s Guide to MATLAB
Line and Point Characteristics (Table 6.2) Line type Line or point color Point type
Symbol Description Symbol Description Symbol Description - -- : -.
Solid Dashed Dotted Dashed-dot
r g b c m y k w
Red Green Blue Cyan Magenta Yellow Black White
+ o * . x s d ^ v > < p h
Plus sign Circle Asterisk Point Cross Square Diamond Upward-pointing triangle Downward-pointing triangle Right-pointing triangle Left-pointing triangle Pentagram Hexagram
Example –
To plot blue dashed lines connecting blue diamonds,
c = 'b--d'
Copyright © Edward B. Magrab 2009
Chapter 6
23
An Engineer’s Guide to MATLAB
Changing Line and Point Attributes –
One has the capability to change the attributes of the lines and points that are being plotted.
These attributes can be changed one of two ways.
The first way is with
plot(u1, v1, c1,'KeyWord', KeyWordValue, …)
where
'KeyWord' is a string expression of the keyword for one of the line and point attributes.
KeyWordValue is either a numerical value or a string expression, depending on 'KeyWord'.
One may use as many pairs of keywords and their values as required.
Copyright © Edward B. Magrab 2009
Chapter 6
24
An Engineer’s Guide to MATLAB
The second way to change the line and point attributes is with the combination of getting the handle to the plotted curve and to then change the attribute using set as follows.
hdl = plot(u1, v1, c1);set(hdl, 'KeyWord', KeyWordValue, …)
We will give examples of this usage subsequently.
Copyright © Edward B. Magrab 2009
Chapter 6
25
An Engineer’s Guide to MATLAB
Use of the Help file to determine the appropriate keywords and their values.
Clicking on Axes brings up the window shown next.
Copyright © Edward B. Magrab 2009
Chapter 6
26
An Engineer’s Guide to MATLAB
Clicking on Core Objects brings up the window shown next.
Copyright © Edward B. Magrab 2009
Chapter 6
27
An Engineer’s Guide to MATLAB
Copyright © Edward B. Magrab 2009
Chapter 6
28
An Engineer’s Guide to MATLAB
Points
To place a red asterisk at the location (2,4), we use
plot(2, 4, 'r*')
Lines
To draw a straight line that goes from (0,0) to (1,2) using the default line type (solid) and the default color (blue), we use
plot([0, 1], [0, 2])
Notice that the first two-element vector [0, 1] represents the values of the x coordinates, and the second two-element vector [0, 2] represents the values of the y coordinates.
1 1.2 1.4 1.6 1.8 2 2.2 2.4 2.6 2.8 33
3.2
3.4
3.6
3.8
4
4.2
4.4
4.6
4.8
5
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
2
Copyright © Edward B. Magrab 2009
Chapter 6
29
An Engineer’s Guide to MATLAB
To draw a set of n unconnected lines whose end points are (x1k,y1k) and (x2k,y2k), k = 1,2,…,n, we create four vectors
1 2
1 2 1,2
j j j jn
j j j jn
x = x x … x
y = y y … y j =
Then, the plot command is
x1 = […]; x2 = […];y1 = […]; y2 = […];plot([x1; x2], [y1; y2])
where [x1; x2] and [y1; y2] are each (2n) arrays.
This plot expression is a generalization of the plotting function stem, which assumes that x1 = x2 and that y1 = 0.
x
y
(x11,y11)
(x21,y21)
(x1n,y1n)
(x2n,y2n)
…
Copyright © Edward B. Magrab 2009
Chapter 6
30
An Engineer’s Guide to MATLAB
Example –
Let us draw four black vertical lines from y = 0 to y = cos(x/20) when x = 2, 4, 6, and 8.
The script is
x = 2:2:8;y = [zeros(1, length(x)); cos(pi*x/20)]; plot([x; x], y, 'k')
where we have used the fact that x1k = x2k, k = 1, …, n.
2 3 4 5 6 7 80
0.2
0.4
0.6
0.8
1
Copyright © Edward B. Magrab 2009
Chapter 6
31
An Engineer’s Guide to MATLAB
Unfortunately, because of automatic scaling of the axes, the first and last lines are coincident with the box around the figure.
Therefore, to adjust the axes so that these lines are visible, we use
axis([xmin, xmax, ymin, ymax])
where xmin, xmax, ymin, and ymax are the minimum and maximum values of the x and y axes, respectively.
2 3 4 5 6 7 80
0.2
0.4
0.6
0.8
1
ymin
ymax
xmin xmax
Copyright © Edward B. Magrab 2009
Chapter 6
32
An Engineer’s Guide to MATLAB
The revised script is
x = 2:2:8;y = [zeros(1, length(x)); cos(pi*x/20)];plot([x; x], y, 'k')axis([1, 9, 0, 1])
1 2 3 4 5 6 7 8 90
0.2
0.4
0.6
0.8
1
2 3 4 5 6 7 80
0.2
0.4
0.6
0.8
1
vs.
Example – continued
Copyright © Edward B. Magrab 2009
Chapter 6
33
An Engineer’s Guide to MATLAB
To place a red square at the end of each vertical line that is off the x-axis, we have to add another triplet of instructions in the plot command
Thus, the script becomes
x = 2:2:8;y = [zeros(1, length(x)); cos(pi*x/20)];plot([x; x], y, 'k', x, cos(pi*x/20), 'rs')axis([1, 9, 0, 1])
1 2 3 4 5 6 7 8 90
0.2
0.4
0.6
0.8
1
Example – continued
Copyright © Edward B. Magrab 2009
Chapter 6
34
An Engineer’s Guide to MATLAB
To change the square with red edges to a solid red square with a blue edges that is larger than the default size, we use the Help file to find that the governing keywords are
MarkerEdgeColorMarkerFaceColorMarkerSize
Hence, the script becomes
x = 2:2:8;y = [zeros(1, length(x)); cos(pi*x/20)];plot([x; x], y, 'k')hold onplot(x, cos(pi*x/20), 's', 'MarkerEdgeColor', 'b', …
'MarkerFaceColor', 'r', 'MarkerSize', 14)axis([1, 9, 0, 1])
Example – continued
Copyright © Edward B. Magrab 2009
Chapter 6
35
An Engineer’s Guide to MATLAB
1 2 3 4 5 6 7 8 90
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
Copyright © Edward B. Magrab 2009
Chapter 6
36
An Engineer’s Guide to MATLAB
Circles
To draw a circle of radius r whose center is located at (a, b) in a Cartesian coordinate system, one has to first transform the radial coordinates to Cartesian coordinates using
cos( )
sin( )
x = a + r θ
y = b + r θ
where 0 1 2.
When 1 < 2, we draw an arc of a circle.
If we assume that 1 = 2, a = 1, b = 2, and r = 0.5, then the script to draw the circle is
Copyright © Edward B. Magrab 2009
Chapter 6
37
An Engineer’s Guide to MATLAB
theta = linspace(0, 2*pi);plot(1+0.5*cos(theta), 2+0.5*sin(theta))axis equal
The axis equal function proportions the graph so that the circles appear as circles, rather than as ellipses.
0.4 0.6 0.8 1 1.2 1.4 1.6
1.6
1.7
1.8
1.9
2
2.1
2.2
2.3
2.4
Example – continued
Copyright © Edward B. Magrab 2009
Chapter 6
38
An Engineer’s Guide to MATLAB
The script to draw a family of six concentric circles, whose initial radius of 0.5 increases in increments of 0.25 and whose centers are indicated by a plus sign, is
theta = linspace(0, 2*pi, 50); % (150)rad = 0.5:0.25:1.75; % (16)x = 1+cos(theta)'*rad; % (506)y = 2+sin(theta)'*rad; % (506)plot(x, y, 'k', 1, 2, 'k+')axis equal
Recall that MATLAB operateson matrices on column by column basis.
-1 0 1 2 3
0.5
1
1.5
2
2.5
3
3.5
Example – continued
Copyright © Edward B. Magrab 2009
Chapter 6
39
An Engineer’s Guide to MATLAB
Family of Curves
In general, MATLAB allows one to have the x-axis represented by a vector and the y-axis by a matrix.
It will draw the curves by drawing the vector versus either the columns or the rows of the matrix, depending on which one matches the length of the vector.
Copyright © Edward B. Magrab 2009
Chapter 6
40
An Engineer’s Guide to MATLAB
Example –
Draw a family of parabolas 2 2y = a - x
The script is
x = 5:0.2:5; % (151)a = 1:5; % (15)[xx, aa] = meshgrid(x.^2, a.^2); % (551)plot(x, aaxx, 'k')
for 5 x 5 in increments 0.2 and a = 1, 2, …, 5
-5 0 5-30
-20
-10
0
10
20
30
Note: MATLAB plots this expression by using the length of x and matching this length with the same length of either the row or column of the array aa-xx.
Copyright © Edward B. Magrab 2009
Chapter 6
41
An Engineer’s Guide to MATLAB
Example –
Visualize of the convergence of the series
2=1
1N
Nj
S =(a + j)
for N = 1, 2, …, 10 and a = 1, 2, and 3.
The script is
aa = 1:3; % (13)N = 1:10; % (110)[a, k] = meshgrid(aa, N); % (103)S = cumsum(1./(a+k).^2); % (103)plot(N, S, 'ks-')
Copyright © Edward B. Magrab 2009
Chapter 6
42
An Engineer’s Guide to MATLAB
0 2 4 6 8 100
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Copyright © Edward B. Magrab 2009
Chapter 6
43
An Engineer’s Guide to MATLAB
Multiple Functions Plotted on One Figure
Consider the three functions2
1
22
-0.33
( ) = 0.1
( ) = cos
( ) = z
g x x
g y y
g z e
where 0 x , y , z 3.5.
We can draw these three functions on one figure in either of three ways -
Copyright © Edward B. Magrab 2009
Chapter 6
44
An Engineer’s Guide to MATLAB
x = linspace(0, 3.5);plot(x, [0.1*x.^2; cos(x).^2; exp(-0.3*x)], 'k')
or
x = linspace(0, 3.5);plot(x, 0.1*x.^2, 'k', x, cos(x).^2, 'k', x, exp(-0.3*x), 'k')
or
x = linspace(0, 3.5);plot(x, 0.1*x.^2, 'k')hold onplot(x, cos(x).^2, 'k')plot(x, exp(-0.3*x), 'k')
0 0.5 1 1.5 2 2.5 3 3.50
0.2
0.4
0.6
0.8
1
1.2
1.4
Note: Color specification is required.
Example – continued
Copyright © Edward B. Magrab 2009
Chapter 6
45
An Engineer’s Guide to MATLAB
If the range of the independent variable for each of these functions is different, then only the second and third scripts can be used.
For example, if 0 x 3, 1 y 4, and 2 z 5, then
x = linspace(0, 3, 45);y = linspace(1, 4, 55);z = linspace(2, 5, 65);plot(x, 0.1*x.^2, 'k-', y, cos(y).^2, 'b--', z, exp(-0.3*z), 'r-.')
Example – continued
Copyright © Edward B. Magrab 2009
Chapter 6
46
An Engineer’s Guide to MATLAB
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 50
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
Copyright © Edward B. Magrab 2009
Chapter 6
47
An Engineer’s Guide to MATLAB
Changing Graph Appearance
box, grid, and axis
Several functions can be used to change the appearance of a graph -
axis on or axis off [default – on]
box on or box off [default – on]
grid on or grid off [default – off]
The function box on only works when axis on has been selected.
Copyright © Edward B. Magrab 2009
Chapter 6
48
An Engineer’s Guide to MATLAB
th = linspace(0, 2*pi, 101); x = sin(th);y = sin(2*th+pi/4);plot(x, y, 'k-')box ongrid on
th = linspace(0, 2*pi, 101); x = sin(th);y = sin(2*th+pi/4);plot(x, y, 'k-')box offgrid offaxis off
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
Copyright © Edward B. Magrab 2009
Chapter 6
49
An Engineer’s Guide to MATLAB
th = linspace(0, 2*pi, 101); x = sin(th);y = sin(2*th+pi/4);plot(x, y, 'k-')box offgrid off
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
Copyright © Edward B. Magrab 2009
Chapter 6
50
An Engineer’s Guide to MATLAB
Special Purpose Graphs
MATLAB has a library of special purpose graphs that are applicable to a wide variety of applications.
We shall briefly illustrate them by having each of them plot some part of the following expression.
(Ω)(Ω) = (Ω) Ω 0jθF H e
where < 1 and
2 22
-12
1(Ω) =
1- Ω + 2 Ω
2 Ω(Ω) = tan
1- Ω
Hζ
ζθ
Copyright © Edward B. Magrab 2009
Chapter 6
51
An Engineer’s Guide to MATLAB
We first create the function FOm to represent this expression
function [H, T] = FOm(Om, z)T = atan2(2*z*Om, 1-Om.^2)*180/pi;H = 1./sqrt((1-Om.^2).^2+(2*z*Om).^2);
where T = () is expressed in degrees, z = , and we have used the two argument form of the arctangent function because of the sign change in the denominator.
2 22
-12
1(Ω) =
1- Ω + 2 Ω
2 Ω(Ω) = tan
1- Ω
Hζ
ζθ
Copyright © Edward B. Magrab 2009
Chapter 6
52
An Engineer’s Guide to MATLAB
semilogx, semilogy, and loglog
semilogx plots the x-axis on a log to the base 10 scale
semilogy plots the y-axis on a log to the base 10 scale
loglog plots both axes on the log to the base 10 scale
Copyright © Edward B. Magrab 2009
Chapter 6
53
An Engineer’s Guide to MATLAB
Om = linspace(0.01, 10, 200); [H, T] = FOm(Om, 0.05);semilogx(Om, H)
Om = linspace(0.01, 10, 200);[H, T] = FOm(Om, 0.05);semilogy(Om, H)
10-2
10-1
100
101
0
1
2
3
4
5
6
7
8
9
10
0 1 2 3 4 5 6 7 8 9 1010
-2
10-1
100
101
Copyright © Edward B. Magrab 2009
Chapter 6
54
An Engineer’s Guide to MATLAB
Om = linspace(0.01, 10, 200);[H, T] = FOm(Om, 0.05);loglog(Om, H)
10-2
10-1
100
101
10-2
10-1
100
101
Copyright © Edward B. Magrab 2009
Chapter 6
55
An Engineer’s Guide to MATLAB
Om = linspace(0.01, 2, 50);[H, T] = FOm(Om, 0.05);stairs(Om, H)
stairs, stem, and bar
Om = linspace(0.01, 2, 30);[H, T] = FOm(Om, 0.05);stem(Om, H)
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 20
1
2
3
4
5
6
7
8
9
10
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 20
1
2
3
4
5
6
7
8
9
Copyright © Edward B. Magrab 2009
Chapter 6
56
An Engineer’s Guide to MATLAB
Om = linspace(0.01, 2, 30);[H, T] = FOm(Om, 0.05);bar(Om, H, 0.6)
width of bar – default = 0.8(20% of bar width is white space)
-0.5 0 0.5 1 1.5 2 2.50
1
2
3
4
5
6
7
8
9
Copyright © Edward B. Magrab 2009
Chapter 6
57
An Engineer’s Guide to MATLAB
plotyy
Creates a graph that consists of a plot of two different functions each with two different ranges of x and y values. The function is
plotyy(x1, y1, x2, y2, 'function_1', 'function_2')
where 'function_1' and 'function_2' each can be
plot, semilogx, semilogy, loglog, or stem
This plot function is equivalent to
function_1(x1, y1)hold onfunction_2(x2, y2)
where function_n is any one of the five functions mentioned previously.
Copyright © Edward B. Magrab 2009
Chapter 6
58
An Engineer’s Guide to MATLAB
Example –
We will plot H() and () on the same graph.
The script is
Om = logspace(-1, 1, 200);[H, T] = FOm(Om, 0.05);plotyy(Om, H, Om, T, 'loglog', 'semilogx')
10-1
100
101
10-2
10-1
100
101
10-1
100
1010
20
40
60
80
100
120
140
160
180
Copyright © Edward B. Magrab 2009
Chapter 6
59
An Engineer’s Guide to MATLAB
convhull, delauney, and voronoi
convhull –
Plots the convex hull of a set of points, which is the smallest polygon that encloses a set of points in a plane, provided that all the points are not collinear.
delauney –
Uses a procedure on a set of points in a plane to create a set of triangles such that no points are contained in any triangle's circumscribed circle.
A circumscribed circle is a circle on whose perimeter the three vertices of a triangle lie.
The output of delauney is plotted using triplot, a special plotting function used to plot triangles in a plane.
Copyright © Edward B. Magrab 2009
Chapter 6
60
An Engineer’s Guide to MATLAB
For each point P in a set of points in a plane, the function voronoi –
draws a convex polygon around each P such that each line segment of the polygon that separates P from each of its closest neighboring points is the perpendicular bisector between P and those nearest neighbors.
Example –
To illustrate these three functions, we create the following function M file that contains a set of x-y coordinate pairs.
function [x, y] = PointSetx = [1, 3, 5, 2, 4, 6, 7, 9, 10, 8, 11];y = [ 4, 6, 7, 1, 2, 10, 8, 3, 11, 5, 9];
Copyright © Edward B. Magrab 2009
Chapter 6
61
An Engineer’s Guide to MATLAB
[x, y] = PointSet;n = convhull(x, y);plot(x(n),y(n), 'k-', x, y, 'ok')axis equal
[x, y] = PointSet;tr = delaunay(x,y);triplot(tr,x,y,'k')hold onaxis equalplot(x, y, 'ok')
Copyright © Edward B. Magrab 2009
Chapter 6
62
An Engineer’s Guide to MATLAB
[x, y] = PointSet;voronoi(x, y, 'ko')axis equal
0 2 4 6 8 10 121
2
3
4
5
6
7
8
9
10
11
Copyright © Edward B. Magrab 2009
Chapter 6
63
An Engineer’s Guide to MATLAB
pie and pie3
Pie charts are created with
pie(d, expl, label)
and
pie3(d, expl, label)
where
d is a vector of length n from which the pie chart will constructed.
expl is an optional vector of length n consisting of 1’s and 0’s to indicate which pie sectors are to be ‘exploded’ (separated from the pie).
label is an optional cell of length n that gives the labels for each pie sector.
Copyright © Edward B. Magrab 2009
Chapter 6
64
An Engineer’s Guide to MATLAB
dat = [39, 10, 1];pie(dat) % or pie3(…)
78%
20%
2%
20%
78%
2%
pie pie3
Copyright © Edward B. Magrab 2009
Chapter 6
65
An Engineer’s Guide to MATLAB
dat = [39, 10, 1];pie(dat, [1, 1, 0] ) % or pie3(…)
78%
20%
2%
20%
78%
2%
pie pie3
Copyright © Edward B. Magrab 2009
Chapter 6
66
An Engineer’s Guide to MATLAB
dat = [39, 10, 1];dat = 100*dat/sum(dat);A = ['Operational ' num2str(dat(1)) ' %'];B = ['Initial ' num2str(dat(2)) ' %'];C = ['R&D ' num2str(dat(3)) ' %'];colormap('cool')pie(dat, [1, 1, 0],{A, B, C}) % or pie3(…)
pie pie3
Copyright © Edward B. Magrab 2009
Chapter 6
67
An Engineer’s Guide to MATLAB
Reading, Displaying, and Manipulating Digital Images
MATLAB can read 14 different digital image formats, some of the more common being –
jpeg (joint photographic experts group)
bmp (Windows bit map)
tiff (tagged image file format)
gif (graphics interchange format)
The digital images are read with
A = imread('FileName', 'fmt')
where FileName is the name of the file containing the digital image in the format specified by fmt.
Copyright © Edward B. Magrab 2009
Chapter 6
68
An Engineer’s Guide to MATLAB
The array A is an (N×M×3) array where
(n×m) is the location of a pixel within this array.
A(n, m, 1), A(n, m, 2), and A(n, m, 3) are components of the red-green-blue (RGB) triplet for each pixel.
The values of each of these three components of the triplet vary from 0 to 255.
For example, the color yellow is expressed as
A(n, m, 1) = 255A(n, m, 2) = 255A(n, m, 3) = 0
Copyright © Edward B. Magrab 2009
Chapter 6
69
An Engineer’s Guide to MATLAB
A = imread('WindTunnel.jpg', 'jpeg');image(A)axis image off
The size of A is (444×290×3).
Copyright © Edward B. Magrab 2009
Chapter 6
70
An Engineer’s Guide to MATLAB
A = imread('WindTunnel.jpg', 'jpeg');A(250:330, 100:180, 1) = 255;A(250:330, 100:180, 2) = 255;A(250:330, 100:180, 3) = 0;image(A)axis image off
The size of A is (444×290×3).
Copyright © Edward B. Magrab 2009
Chapter 6
71
An Engineer’s Guide to MATLAB
Graph Annotations and Visual Enhancement
We shall illustrate by example how to enhance a graph -
• With axis labels, figure titles, labeled curves, legends, filled areas, and placement of text.
• By altering the attributes of the axes, curve lines, and text.
• By using Greek letters, mathematical symbols, and subscripts and superscripts.
• By positioning one figure inside another figure.
• By using the interactive plotting tools.
• By using animation.
Copyright © Edward B. Magrab 2009
Chapter 6
72
An Engineer’s Guide to MATLAB
Axes and Curve Labels, Figure Titles, Legends, and Text Placement
The functions that are used to label the x and y axes and to place a title above the graph are, respectively,
xlabel(s)
ylabel(s)
title(s)
where s is a string.
The function that places text anywhere in the figure window is
text(x, y, s)
where x and y are the coordinates of where the text given by the string s will be placed.
Copyright © Edward B. Magrab 2009
Chapter 6
73
An Engineer’s Guide to MATLAB
Example –
Let us draw, label, title, and annotate the relationship of two intersecting curves, cos(x) and 1/cosh(x), over the range 0 x 6.
In this range, these two curves intersect at x = 0 and x = 4.73.
We shall also draw a vertical line through the intersecting point x = 4.73 and denote the value of x near this intersection.
The script to perform these operations is
Copyright © Edward B. Magrab 2009
Chapter 6
74
An Engineer’s Guide to MATLAB
x = linspace(0, 6, 100); plot(x, cos(x), 'k', x, 1./cosh(x), 'k', [4.73, 4.73], [-1, 1], 'k') xlabel('x') ylabel('Value of functions') title('Visualization of two intersecting curves') text(4.8, -0.1, 'x = 4.73') text(2.1, 0.3, '1/cosh(x)') text(1.2, -0.4, 'cos(x)')
Note – coordinates for the text placements have been found interactively (i.e., with a little trial and error).
Copyright © Edward B. Magrab 2009
Chapter 6
75
An Engineer’s Guide to MATLAB
0 1 2 3 4 5 6-1
-0.5
0
0.5
1
x
Val
ue
of
fun
ctio
ns
Visualization of two intersecting curves
x = 4.73
1/cosh(x)
cos(x)
title('Visualization of two intersecting curves')
xlabel('x')
ylabel('Value of functions')
text(4.8,-0.1, 'x = 4.73')
text(2.1, 0.3, '1/cosh(x)')
text(1. 2, -0.4, 'cos(x)')
plot(x, cos(x), 'k', x, 1./cosh(x), 'k', [4.73 4.73], [-1 1], 'k')
Copyright © Edward B. Magrab 2009
Chapter 6
76
An Engineer’s Guide to MATLAB
Another way to identify the curves is with
legend(s1, s2, …, sn, 'Location', 'Keyword')
where
s1, etc, are the strings containing the alphanumeric identifier for each line that will appear in the legend box in the order that they are drawn.
Keyword is an optional string that places the legend in one of the 8 predetermined locations on the graph.
The number of arguments of legend is less than or equal to the number of different lines being drawn by one or more plot functions.
The legend has to be placed after all the plot functions have been executed.
Copyright © Edward B. Magrab 2009
Chapter 6
77
An Engineer’s Guide to MATLAB
The box around the legend can be toggled on and off with
legend('boxon') % Default
and
legend('boxoff')
'Keyword' = Default location
'North'
'West' 'East'
'South'
'NorthEast' 'NorthWest'
'SouthWest' 'SouthEast'
Copyright © Edward B. Magrab 2009
Chapter 6
78
An Engineer’s Guide to MATLAB
legend differs from text in that text can be used as many times as practical, whereas legend can only be used once.
Also, legend places all the text within a box.
Example –
x = linspace(0,6, 100); plot(x, cos(x), 'k-', x, 1./cosh(x), 'k--',
[4.73, 4.73], [-1, 1], 'k') xlabel('x') ylabel('Value of functions') title('Visualization of two intersecting curves') text(4.8, -0.1, 'x = 4.73') legend('cos(x) ', '1/cosh(x) ', 'Location', 'Southwest')
Copyright © Edward B. Magrab 2009
Chapter 6
79
An Engineer’s Guide to MATLAB
0 1 2 3 4 5 6-1
-0.5
0
0.5
1
x
Val
ue o
f fun
ctio
ns
Visualization of two intersecting curves
x = 4.73
cos(x)1/cosh(x)
Copyright © Edward B. Magrab 2009
Chapter 6
80
An Engineer’s Guide to MATLAB
Filling Regions
A region of a graph can be highlighted by coloring it or by using some geometrical element to identify it.
To fill the area contained within a polygonal region, we use
fill(x, y, c)
where
x and y are arrays of the same length that represent the end point of the lines that form a closed polygon
c is a string indicating the color of the fill (recall Table 6.2)
Copyright © Edward B. Magrab 2009
Chapter 6
81
An Engineer’s Guide to MATLAB
Example –
We modify the previous script so that the area between the two curves in the range 0 x 4.73 is filled with the color cyan.
x = linspace(0,6, 100); plot(x, cos(x), 'k-', x, 1./cosh(x), 'k--',
[4.73, 4.73], [-1, 1], 'k') xlabel('x') ylabel('Value of functions') title('Visualization of two intersecting curves') text(4.8, -0.1, 'x = 4.73') legend('cos(x) ', '1/cosh(x) ', 'Location', 'Southwest')xn = linspace(0, 4.73, 50);hold on fill([xn, fliplr(xn)], [1./cosh(xn), …
fliplr(cos(xn))], 'c');
Copyright © Edward B. Magrab 2009
Chapter 6
82
An Engineer’s Guide to MATLAB
0 1 2 3 4 5 6-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
x
Val
ue o
f fun
ctio
ns
Visualization of two intersecting curves
x = 4.73
cos(x)1/cosh(x)
Copyright © Edward B. Magrab 2009
Chapter 6
83
An Engineer’s Guide to MATLAB
The use of fill to plot two or more overlapping areas becomes dependent on the order of fill within the script.
Additionally, fill has a transparency adjustment that permits two filled overlapping areas to show through a specified amount:
from 0, which is transparent (invisible) to 1, which is opaque (no transparency)
To obtain transparency, two keywords are required:
FaceVertexAlphaData, which in our case will be a single number between 0 and 1.
FaceAlpha, which must be set to 'flat' when FaceVertexAlphaData is equal to a single number.
Copyright © Edward B. Magrab 2009
Chapter 6
84
An Engineer’s Guide to MATLAB
t = linspace(0, 2*pi);fill(t, 0.5*sin(2*t), 'y')hold onfill(t, sin(t), 'm')axis off
t = linspace(0, 2*pi);fill(t, sin(t), 'm')hold onfill(t, 0.5*sin(2*t), 'y')axis off
Copyright © Edward B. Magrab 2009
Chapter 6
85
An Engineer’s Guide to MATLAB
t = linspace(0, 2*pi);fill(t, 0.5*sin(2*t), 'y')hold onfill(t, sin(t), … 'm', 'FaceVertexAlphaData', 0.6, … 'FaceAlpha', 'Flat')axis off
t = linspace(0, 2*pi);fill(t, 0.5*sin(2*t), 'y')hold onfill(t, sin(t), … 'm', 'FaceVertexAlphaData', 1, … 'FaceAlpha', 'Flat')axis off Opaque
Copyright © Edward B. Magrab 2009
Chapter 6
86
An Engineer’s Guide to MATLAB
t = linspace(0, 2*pi);fill(t, 0.5*sin(2*t), 'y')hold onfill(t, sin(t), … 'm', 'FaceVertexAlphaData', 0.0, … 'FaceAlpha', 'Flat')axis off Invisible
Copyright © Edward B. Magrab 2009
Chapter 6
87
An Engineer’s Guide to MATLAB
patch
patch gives a little more control over the attributes of it boundary edges and is given by
patch(x, y, c)
where its arguments have the same meaning as those for fill.
This function also can adjust its transparency properties for overlapping patches in the same manner as is done for fill.
We shall illustrate the use of patch by drawing two squares that are generated by the following function.
Copyright © Edward B. Magrab 2009
Chapter 6
88
An Engineer’s Guide to MATLAB
function [x y] = ptc(a, b, e)x = a+ [0 0 e e 0];y = b + [0 e e 0 0];
where
a and b are the distances from the origin along the x and y axes, respectively
e is the length of the edges of the square
Copyright © Edward B. Magrab 2009
Chapter 6
89
An Engineer’s Guide to MATLAB
[x1, y1] = ptc(0, 0, 1);[x2, y2] = ptc(0.5, 0.5, 1.5);patch(x1, y1, 'y')patch(x2, y2, 'g')axis off
[x1, y1] = ptc(0, 0, 1);[x2, y2] = ptc(0.5, 0.5, 1.5);patch(x1, y1, 'y', 'EdgeColor', 'b',… 'LineWidth', 2.5, … 'FaceVertexAlphaData', 0.6, … 'FaceAlpha', 'Flat')patch(x2, y2, 'g', 'EdgeColor', 'r', … 'LineWidth', 3.5)axis off
No transparency
Transparency and altered edge attributes
Copyright © Edward B. Magrab 2009
Chapter 6
90
An Engineer’s Guide to MATLAB
Greek Letters, Mathematical Symbols, Subscripts, and Superscripts
• MATLAB provides the capability to annotate a graph with upper- and lower-case Greek letters, subscripts and superscripts, and a range of mathematical symbols.
• These annotations can be done within xlabel, ylabel, text, legend, and title.
• The formatting instructions follow the LaTeX language.
• All the following techniques are only valid within a pair of apostrophes.
Copyright © Edward B. Magrab 2009
Chapter 6
91
An Engineer’s Guide to MATLAB
Upper and Lower Case Greek Letters and Some Mathematical Symbols (Table 6.10)
Lower case Upper case Mathematical
Symbol Syntax Symbol Syntax Symbol Syntax Symbol Syntax Symbol Syntax
\alpha \beta \gamma \delta \epsilon \zeta \eta \theta \iota \kappa \lambda \mu
\nu \xi o \pi \rho \sigma \tau \upsilon \phi \chi \psi \omega
\Gamma \Delta \Theta \Lambda \Xi \Pi \Sigma \Upsilon \Phi \Psi \Omega
\leq \geq \neq \pm \times \infty \sum
\int
\div
\sim
\leftarrow
\uparrow
<< >> ' # $ % & {
\circ \ll \gg \prime \Leftarrow \angle \surd \# \$ \% \& \{
Copyright © Edward B. Magrab 2009
Chapter 6
92
An Engineer’s Guide to MATLAB
• Subscripts are created with the underscore (_).
• Superscripts with the exponentiation operator (^).
• Greek letters are obtained by the spelling of the letter and preceding the spelling by a backslash (\).
Upper-case Greek letters are obtained by capitalizing the first letter of the spelling.
• Since many of the upper-case Greek letters are the same as upper-case English letters, upper case Greek letters are obtained by using the appropriate upper case English letters.
• When groups of symbols are to be kept together they are placed between a pair of braces ({}).
Copyright © Edward B. Magrab 2009
Chapter 6
93
An Engineer’s Guide to MATLAB
Note –
None of these Greek letters, mathematical symbols, subscripts, and superscripts will work when displayed to the command window; that is, when using disp or fprint.
Copyright © Edward B. Magrab 2009
Chapter 6
94
An Engineer’s Guide to MATLAB
The alphanumeric characters can be made bold by preceding the alphanumeric characters with
\bf
To make the alphanumeric characters italic, we use
\it
and to return either of these changes to normal, we use
\rm
Copyright © Edward B. Magrab 2009
Chapter 6
95
An Engineer’s Guide to MATLAB
Example –
We shall compute and plot the following function for = 3 and 1 x 2, and label the figure accordingly.
Om1 = linspace(1, 2); beta = 3;plot(Om1, cos(4*pi*Om1).*exp(-(1+Om1.^beta)), 'k')title('\itg_{\rm2} \rmversus \Omega_1 for
\it\beta \rm= 3')ylabel('\itg_{\rm2}')xlabel('\Omega_1')text(1.2, 0.08, '\itg_{\rm2}\rm=cos(\Omega_1)\ite^{\rm-
(1+\Omega_1^{\it\beta\rm})}')
1(1 )2 1cos(4 )g e
Copyright © Edward B. Magrab 2009
Chapter 6
96
An Engineer’s Guide to MATLAB
1 1.2 1.4 1.6 1.8 2-0.06
-0.04
-0.02
0
0.02
0.04
0.06
0.08
0.1
0.12
0.14
g2 versus
1 for = 3
g 2
1
g2=cos(
1)e-(1+
1
)
ylabel('\itg_{\rm2}')
title('\itg_{\rm2} \rmversus \Omega_1 for \it\beta \rm= 3')
text(1.2, 0.08, '\itg_{\rm2}\rm=cos(\Omega_1)\ite^{\rm-1+\Omega_1^{\it\beta\rm})}')
xlabel('\Omega_1')
Copyright © Edward B. Magrab 2009
Chapter 6
97
An Engineer’s Guide to MATLAB
Altering the Attributes of Axes, Curves, and Text
Changes to virtually all characteristics of the elements that comprise a graph can be made.
We shall consider the following –
For lines:
width and color
For the text in axis labels, titles, placed text, and legends:
font, alignment, size, type, characteristics, and color
For axes:
line width and text attributes
Copyright © Edward B. Magrab 2009
Chapter 6
98
An Engineer’s Guide to MATLAB
Default values
Line width for the axes and drawn curves: 0.5 pt
Font size for labels, placed text, and titles: 10 pt
Font name for the axis labels and numbering, titles, and legend: Helvetica
Changes
The attributes for
xlabel, ylabel, title, and text
are changed by adding any number of pairs of keywords and their values to the arguments of these functions.
Copyright © Edward B. Magrab 2009
Chapter 6
99
An Engineer’s Guide to MATLAB
xlabel(s, 'Keyword', KeyWordValue, …)
ylabel(s, 'Keyword', KeyWordValue, …)
title(s, 'Keyword', KeyWordValue, …)
text(x, y, s, 'Keyword', KeyWordValue, …)
where
ss is the string to be displayed.
'KeyWord' is a string containing the key word.
KeyWordValue is the value expressed as a string or a numerical value, depending on the key word.
x, y are the coordinates of the text placement.
Copyright © Edward B. Magrab 2009
Chapter 6
100
An Engineer’s Guide to MATLAB
Text Key Words and Attributes for Text Positioning (Table 6.11)
Keyword Keyword value Example 'HorizontalAlignment' 'Left'
'Center' 'Right'
Left
Right
Center
'VerticalAlignment' 'Top' 'Middle' 'Bottom'
Top
Bottom Middle
'Rotation' 0 to 360 or 180 to +180 9
0
180 or -180
-90
or 2
70
0 or 360
Copyright © Edward B. Magrab 2009
Chapter 6
101
An Engineer’s Guide to MATLAB
Additional Key Words and Attributes for Text(Table 6.12)
Copyright © Edward B. Magrab 2009
Chapter 6
102
An Engineer’s Guide to MATLAB
Keywords and Attributes for legend Handles(Table 6.13)
Handle name Keyword Keyword value Attribute affected
a(1) 'LineWidth' Number > 0 (default: 0.5) Thickness of legend box edges
a(1) 'Color' 'Letter from 2nd column of Table 6.2'
Background color of legend box
b(1), b(2) 'FontSize' Number > 0 (default: 10) Font size of legend text
b(1), b(2) 'FontName' 'Courier' 'Helvetica' (default) 'Times' (Times roman)
Font type of legend text
b(1), b(2) 'Color' 'Letter from 2nd column of Table 6.2'
Color of legend text
Copyright © Edward B. Magrab 2009
Chapter 6
103
An Engineer’s Guide to MATLAB
Key Words and Attributes for Lines (Table 6.14)
Key word Keyword value
'Linewidth' Number > 0 (default: 0.5) 'Color' 'Letter from 2nd column of
Table 6.2'
Copyright © Edward B. Magrab 2009
Chapter 6
104
An Engineer’s Guide to MATLAB
To set the attributes for curves created by plot and for the text appearing in legend, we require the function handles to legend and plot.
To alter the width of the axis line and the tick mark labels we use set and gca, which gets the handle for the current axis.
The set function sets a specific property associated with a function handle.
To get the function handles for legend and plot, we use
hdl = plot(…);
[lh, lo] = legend(…);
where plot and legend perform in the manner already discussed and hdl is the handle to the curve plotted, and lo(1) is the handle to the text appearing in legend.
Copyright © Edward B. Magrab 2009
Chapter 6
105
An Engineer’s Guide to MATLAB
The set function is
set(hdl, 'Keyword', KeyWordValue, …)
where
hdl is the handle.
'KeyWord' is a string containing the key word.
KeyWordValue is the string or numerical value that corresponds to the key word.
Copyright © Edward B. Magrab 2009
Chapter 6
106
An Engineer’s Guide to MATLAB
Example –
We shall make the -
Background color of the legend box yellow.
Thickness of the box’s edges 2 points.
Size of the text increased to 14 points.
Text for the solid curve will be blue and that for the dashed curve will be red.
Independent variable x will be in italics.
Copyright © Edward B. Magrab 2009
Chapter 6
107
An Engineer’s Guide to MATLAB
x = linspace(0, 6, 100); plot(x, cos(x), 'k-', x, 1./cosh(x), 'k--', [4.73, 4.73], …
[-1, 1], 'k') xlabel('x') ylabel('Amplitude') title('Visualization of two intersecting curves') text(4.8, -0.1, 'x = 4.73') [a, b] = legend('cos(\itx\rm)', '1/cosh(\itx\rm)', 'Location',
'SouthWest');set(a(1), 'LineWidth', 2, 'Color', 'y')set(b(1), 'fontsize', 14, 'Color', 'b')set(b(2), 'fontsize', 14, 'Color', 'r')
Copyright © Edward B. Magrab 2009
Chapter 6
108
An Engineer’s Guide to MATLAB
0 1 2 3 4 5 6-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
x
Am
plitu
de
Visualization of two intersecting curves
x = 4.73
cos(x)1/cosh(x)
0 1 2 3 4 5 6-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
x
Am
plitu
de
Visualization of two intersecting curves
x = 4.73
cos(x)1/cosh(x)
cos(x)
1/cosh(x)
Copyright © Edward B. Magrab 2009
Chapter 6
109
An Engineer’s Guide to MATLAB
Example –
We shall modify the script to make the following alterations to
Title: 14 pt courier, bold facex-axis label: 14 pt times roman, italic, and bold facey-axis label: 14 pt HelveticaPlaced text: 12 pt standard mathematical notationAxes lines: 1.5 pt wideAxes text: 14 pt Helvetica Curve for cos(x): 4 pt line widthCurve for cosh(x): 2.5 pt line widthVertical line at x = 4.73: 0.25 line width, green
0 1 2 3 4 5 6-1
-0.5
0
0.5
1
x
Val
ue o
f fun
ctio
ns
Visualization of two intersecting curves
x = 4.73
cos(x)1/cosh(x)
Copyright © Edward B. Magrab 2009
Chapter 6
110
An Engineer’s Guide to MATLAB
x = linspace(0, 6,100); hc = plot(x, cos(x), 'k-'); hold onhch = plot(x, 1./cosh(x), 'k--'); hsl = plot( [4.73, 4.73], [-1, 1], 'k'); [a, b] = legend('cos(x) ', '1/cosh(x) ', 'Location', 'SouthWest');xlabel('\it\bfx', 'FontSize', 14, 'FontName', 'Times') ylabel('Value of functions', 'FontSize', 14) title('\bfVisualization of two intersecting curves', 'FontName',
'Courier', 'FontSize', 14) text(4.8, -0.1, '\itx \rm= 4.73','FontName', 'Times', 'FontSize', 12) set(hc, 'LineWidth', 4)set(hch, 'LineWidth', 2.5)set(hsl, 'LineWidth', 0.25, 'Color', ‘g')set(gca, 'FontSize', 14, 'LineWidth', 1.5)set(b(1), 'FontSize', 10)
Copyright © Edward B. Magrab 2009
Chapter 6
111
An Engineer’s Guide to MATLAB
Note: This figure has several distracting attributes and, therefore, is visually ineffective.
0 1 2 3 4 5 6-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
x
Val
ue o
f fun
ctio
ns
Visualization of two intersecting curves
x = 4.73
cos(x)
1/cosh(x)
Copyright © Edward B. Magrab 2009
Chapter 6
112
An Engineer’s Guide to MATLAB
Inserting a Figure within a Figure
To insert a figure within a figure we use –
axes('Position', [left, bottom, width, height])
where
Position - keyword
left - x-coordinate of the figure origin (0<left<1)
bottom – y-coordinate of the figure origin (0<bottom<1)
width – width of the figure (0<width<1)
height – height of the figure (0<height<1)
Copyright © Edward B. Magrab 2009
Chapter 6
113
An Engineer’s Guide to MATLAB
Inserted figure
Main figure
0 1 0
1
bottom
left
height
width
axes('Position', [left, bottom, width, height])
Copyright © Edward B. Magrab 2009
Chapter 6
114
An Engineer’s Guide to MATLAB
Example – Response of a single degree-of-freedom system
We shall illustrate axes by displaying the non dimensional displacement response x() of a single degree-of-freedom system subjected to a periodic pulse of period T and pulse duration td in the main
figure and the amplitude of the frequency response function H() of the system in an inserted figure.
If the natural frequency of the system is n, then the
governing relations are
Copyright © Edward B. Magrab 2009
Chapter 6
115
An Engineer’s Guide to MATLAB
1
sin( )( ) 1 2 ( ) sin ( )k k k k
k
kx H
k
where = td/T < 1, k = ko, o = o/n, o = 2/T,
2 22
12
1
1( )
1 2
2( ) tan
1
sin( )tan
0
k
k k
kk
k
k
H
k k
and < 1 is the damping factor.
If we take 200 terms of the series, and assume that = 0.1, , 50 120, and = 0.4, then the script is 0.03 2o
Copyright © Edward B. Magrab 2009
Chapter 6
116
An Engineer’s Guide to MATLAB
k = 1:200; alph = 0.4; xi = 0.1; Omo = 0.03*sqrt(2); N = 400;HOm = inline('1./sqrt((1-(Om*k).^2).^2+(2*xi*Om*k).^2)', 'k',
'Om', 'xi');tau = linspace(-50, 120, N);sn = sin(pi*k*alph)./(pi*k*alph);thn = atan2(2*xi*Omo*k, (1-(Omo*k).^2));psi = atan2(sn, 0);cnt = sin(Omo*k'*tau-repmat(thn', 1, N)+repmat(psi', 1, N));z = alph*(1+2*abs(sn).*HOm(k, Omo, xi)*cnt);plot(tau, z, 'k-')a = axis; a(1) = -50; a(2) = 120;axis(a)xlabel('\tau')ylabel('x(\tau)')axes('Position', [0.62, 0.62, 0.25, 0.25])semilogy(k*Omo, HOm(k, Omo, xi), 'k-')ylabel('H(\Omega)')xlabel('\Omega')box off
Copyright © Edward B. Magrab 2009
Chapter 6
117
An Engineer’s Guide to MATLAB
-40 -20 0 20 40 60 80 100 120-1
-0.5
0
0.5
1
1.5
2
x( )
0 5 1010
-2
10-1
100
101
H(
)
axes('Position', [0.62, 0.62, 0.25, 0.25])axes('Position', [left, bottom, width, height])
Copyright © Edward B. Magrab 2009
Chapter 6
118
An Engineer’s Guide to MATLAB
Interactive Plotting Tools
Changes to the attributes of the text, curves, and axes can be made interactively in the figure window by selecting the appropriate operation from its Tools menu.
After the changes have been made, the figure can be saved as a function M file.
We shall illustrate how to use these interactive tools by using them to make a few modifications to the following program.
x = linspace(-1, 2, 150);plot(x, humps(x), 'k-', [-1, 2], [0, 0], 'b-')
Copyright © Edward B. Magrab 2009
Chapter 6
119
An Engineer’s Guide to MATLAB
Show Plot Tools icon
Copyright © Edward B. Magrab 2009
Chapter 6
120
An Engineer’s Guide to MATLAB
The properties of the x-axis label can be altered by using these menus.
Clicking on this line brings up these menus, which can be used to alter the properties of the line.
Insertx Label
Copyright © Edward B. Magrab 2009
Chapter 6
121
An Engineer’s Guide to MATLAB
Data Cursor
Placing crosshairs here brings up values shown.
Copyright © Edward B. Magrab 2009
Chapter 6
122
An Engineer’s Guide to MATLAB
Right click on these data values to bring
up this menu.
Data Cursor
Copyright © Edward B. Magrab 2009
Chapter 6
123
An Engineer’s Guide to MATLAB
Animation –
The two functions that are used to create a movie are
A(k) = getframe
which captures the kth movie frame of a total of N frames and
movie(A, nF, pbs)
which is used to play nF times the N frames captured in the matrix A by getframe.
This function plays the movie at a playback speed pbs, which, if omitted, uses a default value of 12 frames per second.
Copyright © Edward B. Magrab 2009
Chapter 6
124
An Engineer’s Guide to MATLAB
To create a movie in the avi (audio/video interleaved) format from the movie created by movie, one uses
movie2avi(A, 'FileName.avi', 'KeyWord', 'KeyWordValue');
The variable A is the variable used in movie.
To create movies that can be shown in Microsoft Power Point, we set
'KeyWord' = 'compression'
'KeyWordValue' = 'none'
Copyright © Edward B. Magrab 2009
Chapter 6
125
An Engineer’s Guide to MATLAB
Example – Animation of a slider-crank mechanism
The horizontal distance that the slider moves as a function of the rotation angle of the crank arm a is
22cos sins a b a e
a b e
s
c
d
f
Copyright © Edward B. Magrab 2009
Chapter 6
126
An Engineer’s Guide to MATLAB
Let:
0 2 at n = 40 equally-spaced positions
a = 1
b = 2.5
e = 0.25
c = 0.5
d = 1
f = 0.06
The number of times that the 40 frames is to be repeated (played over) is 5 (= nF).
Copyright © Edward B. Magrab 2009
Chapter 6
127
An Engineer’s Guide to MATLAB
n = 40; phi = linspace(0, 2*pi, n); a = 1; b = 2.5; e = 0.25; nF = 5;c = 0.5; d = 1; f = 0.06;ax = a*cos(phi); ay = a*sin(phi);s = real(ax+sqrt(b^2-(ay-e).^2));v = [1.1*min(ax), 1.1*(max(s)+d/2) 1.1*min(ay), 1.1*max(ay)];xgnd = [min(ax), max(s)+d/2, max(s)+d/2, min(ax), min(ax)];ygnd = [e, e, e-f, e-f, e];slidery = [e, e+c, e+c, e, e]; % Vertical component of slider
is constant
22cos sins a b a e
a b e
s
c
d
f
Copyright © Edward B. Magrab 2009
Chapter 6
128
An Engineer’s Guide to MATLAB
for k=1:n fill(xgnd, ygnd, 'r') % Thin horizontal bar hold on plot(ax, ay, 'b--', 0, 0, 'ko'); % Dashed circle and center of
circle sliderx = [s(k)-d/2, s(k)-d/2, s(k)+d/2, s(k)+d/2, s(k)-d/2]; fill(sliderx, slidery, 'm'); % Slider position plot([0 ax(k)], [0;ay(k)], 'ko-', 'LineWidth', 2); plot([ax(k), s(k)], [ay(k), e+c/2], 'ko-', 'LineWidth', 2); axis(v) axis off equal SliderCrankFrame(k) = getframe; hold offendmovie(SliderCrankFrame, nF, 30)movie2avi(SliderCrankFrame, 'SliderCrankAvi.avi',
'compression', 'none')
Copyright © Edward B. Magrab 2009
Chapter 6
129
An Engineer’s Guide to MATLAB
Copyright © Edward B. Magrab 2009
Chapter 6
130
An Engineer’s Guide to MATLAB
Example – Polar Plot: Far Field Radiation Pattern of a Sound Source
The normalized sound pressure at a large distance from the center of a circular piston in an infinite baffle that is vibrating at a frequency f is given by
21( )( ) = << and <<
J kaθp r,θ ka r a r
kaθwhere
r is the radial distance from the center of the piston.
is the angle of r with respect to the plane of the
baffle.
k is the wave number.
a is the radius of the piston.
J1(x) is the Bessel function of the first kind of order 1.
Copyright © Edward B. Magrab 2009
Chapter 6
131
An Engineer’s Guide to MATLAB
The wave number is the reciprocal of the wavelength of the sound at frequency f; thus, ka is dimensionless.
This model is a fair approximation to the angular dispersion of sound from a loudspeaker.
We shall create a polar plot of the normalized radiation pattern for ka = 6 when ranges from /2 < < /2.
We have chosen this solution to illustrate the use of polar, which plots results in polar coordinates.
Copyright © Edward B. Magrab 2009
Chapter 6
132
An Engineer’s Guide to MATLAB
The script is
theta = linspace(pi/2, pi/2, 300);p = abs(besselj(1, 6*pi*theta)./(6*pi*theta));polar(theta, p/max(p))axis([-.02, 0.15, -0.05, 0.05]) % Right hand figure
0.2
0.4
0.6
0.8
1
30
210
60
240
90
270
120
300
150
330
180 0
270
300
330
0
Copyright © Edward B. Magrab 2009
Chapter 6
133
An Engineer’s Guide to MATLAB
Example – Multiple Curves: Notch Sensitivity for Steel
We shall plot the notch sensitivity constant q over a range of values for 50 Su 250 and 0 < r < 0.2.
The program consists of two parts –
(1) The values of the coefficients of the fourth-order polynomial used to fit experimental data and the data points and the polynomial that fits these points are displayed.
(2) The polynomial is used to generate a family of curves of notch sensitivity q versus the notch radius r for several values of the ultimate strength of steel Su.
Copyright © Edward B. Magrab 2009
Chapter 6
134
An Engineer’s Guide to MATLAB
Su = linspace(0.34, 1.72, 50); skip = [1, 3, 6, 8, 11];ncs = NeuberData; L = length(skip);p = polyfit(ncs(:,1), ncs(:,2), 4);figure(1)plot(Su, polyval(p, Su), 'k', ncs(:,1), ncs(:,2), 'ks') xlabel('\itS_u')ylabel('\surd\ita')figure(2)[s, r] = meshgrid(ncs(skip,1), linspace(0.1, 5, 80));notch = inline('1./(1+polyval(p, s)./sqrt(r))', 'p', 's', 'r');plot(r, notch(p, s, r), 'k')y(1:L,1) = 1;lab = [repmat('\itS_u= \rm', L, 1) num2str(ncs(skip,1))];text(repmat(1, 1, L), notch(p, ncs(skip,1), y)-0.03, lab)xlabel('\itr')ylabel('\itq')
Copyright © Edward B. Magrab 2009
Chapter 6
135
An Engineer’s Guide to MATLAB
0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.80
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Su
a
Copyright © Edward B. Magrab 2009
Chapter 6
136
An Engineer’s Guide to MATLAB
0 1 2 3 4 5
0.4
0.5
0.6
0.7
0.8
0.9
1
Su= 0.34
Su= 0.62
Su= 1.03
Su= 1.31
Su= 1.72
r
q
Copyright © Edward B. Magrab 2009
Chapter 6
137
An Engineer’s Guide to MATLAB
Example - Stability of a loaded structure
The static equilibrium position of an imperfection-sensitive structure is given by
cot 1 sin 1 sin
1 sin
op
where o is the amount of angular imperfection of the
structure.
For a given value of o, the value of o at which p has
a maximum value is that value at which the system becomes unstable; that is, for o < max o the
system is stable and for those values for which o > max o the system is unstable.
Copyright © Edward B. Magrab 2009
Chapter 6
138
An Engineer’s Guide to MATLAB
function Stabilitytho = [0.001, 0.005, 0.01, 0.02];th = linspace(0.01, 0.2, 200);thmx = zeros(1, length(tho));for k = 1:length(tho) thmx(k) = fminbnd(@prev, 0.01, 0.18, [], tho(k)); indx = find(th<thmx(k)); % Locate stable region plot(th(indx)-tho(k), p(th(indx), tho(k)), 'k--') % Stable region hold on plot(th(indx(end)+1:end)-tho(k), p(th(indx(end)+1:end), tho(k)), 'k-') if k==1 legend('Stable region', 'Unstable region') end plot(thmx(k)-tho(k), p(thmx(k), tho(k)), 'ko', 'MarkerFaceColor', 'k') text(thmx(k)-tho(k)+0.015, p(thmx(k), tho(k))+0.005,
['\theta_o=' num2str(tho(k))]) text(thmx(k)-tho(k)-0.02, p(thmx(k), tho(k))-0.01,
['\theta=' num2str(thmx(k),3)])end
Copyright © Edward B. Magrab 2009
Chapter 6
139
An Engineer’s Guide to MATLAB
plot(thmx-tho, p(thmx, tho), 'k-')v = axis; v(1) = 0; v(3) = 0.32; axis(v)xlabel('\theta-\theta_o')ylabel('p')
function s = p(th, tho)s = cot(th).*(sqrt(1+sin(th))-sqrt(1+sin(tho)))./sqrt(1+sin(th));
function s = prev(th, tho)s = -p(th, tho);
Copyright © Edward B. Magrab 2009
Chapter 6
140
An Engineer’s Guide to MATLAB
0 0.05 0.1 0.15 0.20.32
0.34
0.36
0.38
0.4
0.42
0.44
0.46
0.48
0.5
-o
p
o=0.001
=0.0368
o=0.005
=0.0827
o=0.01
=0.117
o=0.02
=0.167
Stable regionUnstable region
Copyright © Edward B. Magrab 2009
Chapter 6
141
An Engineer’s Guide to MATLAB
-59-61-61
3 0
-48
1
-42
1
-32-33-36
3
-26-28-29-30
4
-20-23-24-24
4
-15-15-17-17-18-18-18
7
-7 -8 -8 -9-10-10-10-11-12-12
10
0 0-1-1-2-2-4-4-4-4-5-5-6-6
14
654443221
9
12121212121211 9 8 7 7
11
171716161616151414131313
12
242323
3
302928272727272626
9
3631
2
413837
3
4645
2
5552
2Nj =
-61 -42.7 -24.4 -6.05 12.3 30.6 48.9
Bin center
100 normally distributed random integers from -61 to 55
= 6.11
Example - Non Traditional Histogram
Copyright © Edward B. Magrab 2009
Chapter 6
142
An Engineer’s Guide to MATLAB
Example - Frequency Response Functions of a Two Degree-of-Freedom System
The frequency-response functions of a two degree-of-freedom system with masses m1 and
m2, stiffness k1 and k2, and damping c1 and c2 and
forcing frequency are determined from
11 21
12 22
( ) ( )( ) , ( )
( ) ( )
( ) ( )( ) , ( )
( ) ( )r r
E j C jH j H j
D j D j
B j A jH j H j
m D j m D j
m1
m2
c1 k1
k1 c1
Hij force on mass j, response of mass i
The magnitudes of the frequency-response functions are given by |Hil(j)|, i, l = 1, 2.
Copyright © Edward B. Magrab 2009
Chapter 6
143
An Engineer’s Guide to MATLAB
where
and
2 21 2
22
22
2 22
4 31 2 2
2 2 2 2 21 2 2 1
( ) 2( ) 1
( ) 2
( ) 2
( ) 2
( ) [2 2 2 ]
[1 4 ] [2 2 ]
r r r r
r r r r
r r
r r
r r r
r r r r r r r
A j m j m
B j m j m
C j j
E j j
D j j m
m j
2 2
1
2
1 1
, 2 1, 2
, 1
l l nnl l r
l l nl n
rn
k cl
m m
mm j
m
Copyright © Edward B. Magrab 2009
Chapter 6
144
An Engineer’s Guide to MATLAB
function Twodofz1 = 0.1; z2 = 0.1; wr = 0.7; mr = 0.6; wend = 2;w = linspace(0, wend, 200);kase = [11, 12, 21, 22];for k=1:4 subplot(2, 2, k) H = tf2dof(w, mr, wr, z1, z2, kase(k)); plot(w, H, 'k-') hold on xlabel('\Omega') ylabel(['|H_{' num2str(kase(k)) '}(\Omega)|']) v = axis; v(2) = wend; axis(v) title(['\zeta_1 = ' num2str(z1) ' \zeta_2 = ' num2str(z2) ... ' m_r = ' num2str(mr) ' \omega_r = ' num2str(wr)])end
Copyright © Edward B. Magrab 2009
Chapter 6
145
An Engineer’s Guide to MATLAB
function H = tf2dof(w, mr, wr, z1, z2, kase)D = w.^4-(2*z1+2*z2*wr.*mr+2*z2*wr)*i.*w.^3 ... -(1+mr.*wr.^2+wr.^2+4*z1*z2*wr).*w.^2 ... +(2*z2*wr+2*z1*wr.^2).*w*i+wr.^2;switch kase case 11 q1 = (-w.^2+2*z2*wr.*w*i+wr.^2)./D; case 12 q1 = (2*z2*wr.*w*i+wr.^2)./D; case 21 q1 = (2*z2*mr*wr*w*i+mr*wr^2)./D/mr; case 22 q1 = (-w.^2+2*(z1+z2*mr*wr)*w*i+1+mr*wr^2)./D/mr;endH = abs(q1);
Copyright © Edward B. Magrab 2009
Chapter 6
146
An Engineer’s Guide to MATLAB
0 0.5 1 1.5 20
1
2
3
4
|H11
()|
1 = 0.1
2 = 0.1 m
r = 0.6
r = 0.7
0 0.5 1 1.5 20
5
10
|H12
()|
1 = 0.1
2 = 0.1 m
r = 0.6
r = 0.7
0 0.5 1 1.5 20
5
10
|H21
()|
1 = 0.1
2 = 0.1 m
r = 0.6
r = 0.7
0 0.5 1 1.5 20
10
20
30
|H22
()|
1 = 0.1
2 = 0.1 m
r = 0.6
r = 0.7
Copyright © Edward B. Magrab 2009
Chapter 6
147
An Engineer’s Guide to MATLAB
Example - Sudoku: Drawing Squares
We shall create a program that produces the following figure.
1 9 8 3 2 5
6 5 4
5
4 5 2
9 2 1 7 6
3 9 1
7
2 4 1
6 1 5 3 9 8
1
9
2
8
3
7
4
6
5
5
6
4
7
3
8
2
9
1
Copyright © Edward B. Magrab 2009
Chapter 6
148
An Engineer’s Guide to MATLAB
% InitializationS = flipud([6, 0, 0 1, 5, 3, 0, 9, 8; ... 2, 0, 0, 0, 0, 4, 0, 1, 0; ... 0, 0, 0, 0, 0, 0, 0, 0, 7; ... 3, 0, 0, 9, 0, 0, 0, 0, 1; ... 9, 0, 0, 2, 1, 7, 0, 0, 6; ... 4, 0, 0, 0, 0, 5, 0, 0, 2; ... 5, 0, 0, 0, 0, 0, 0, 0, 0; ... 0, 6, 0, 5, 0, 0, 0, 0, 4; ... 1, 9, 0, 8, 3, 2, 0, 0, 5]);hold onaxis off equal
Copyright © Edward B. Magrab 2009
Chapter 6
149
An Engineer’s Guide to MATLAB
% Generate squares and fill and number themfor r = 1:9 for c = 1:9 if S(r, c)~=0 fill([c-1, c, c, c-1, c-1], [r-1, r-1, r, r, r-1], 'y',
'LineWidth', 1.5) text(c-0.5, r-0.5, int2str(S(r, c)), 'fontsize', 13,
'HorizontalAlignment','center', ... 'VerticalAlignment','middle') else plot([c-1, c, c, c-1, c-1], [r-1, r-1, r, r, r-1], 'k-', ...
'LineWidth', 1.5) end endend
Copyright © Edward B. Magrab 2009
Chapter 6
150
An Engineer’s Guide to MATLAB
% Label outside gridfor k=1:9 text(k-0.5, -0.3, int2str(k), 'fontsize', 10, …
'HorizontalAlignment', 'center', ... 'VerticalAlignment', 'middle') text(-0.3, k-0.5, int2str(10-k), 'fontsize', 10, …
'HorizontalAlignment', 'center', ... 'VerticalAlignment', 'middle'')endHev = [3, 6];plot([Hev; Hev], [zeros(1, 2); repmat(9, 1, 2)], 'k', …
'linewidth', 3);plot([zeros(1, 2); repmat(9, 1, 2)], [Hev; Hev], 'k', …
'linewidth', 3);