0% found this document useful (0 votes)
2 views61 pages

Lec 5

Chapter 5 of the document focuses on creating and customizing plots using MATLAB/OCTAVE, emphasizing the importance of graphical representation in engineering for data interpretation. It covers two-dimensional and three-dimensional plots, including techniques for labeling, adjusting appearance, and creating subplots. Additionally, it discusses advanced plotting features such as layering multiple plots, handling complex arrays, and customizing line styles and colors.

Uploaded by

chranasajid786
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)
2 views61 pages

Lec 5

Chapter 5 of the document focuses on creating and customizing plots using MATLAB/OCTAVE, emphasizing the importance of graphical representation in engineering for data interpretation. It covers two-dimensional and three-dimensional plots, including techniques for labeling, adjusting appearance, and creating subplots. Additionally, it discusses advanced plotting features such as layering multiple plots, handling complex arrays, and customizing line styles and colors.

Uploaded by

chranasajid786
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/ 61

Islamic University in Al-Madinah

Electrical Engineering
Department

Chapter 5

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 1


Amer
Contents of this Chapter
After reading this chapter, you should be able to:
ü Create and label two dimensional plots

ü Adjust the appearance of your plots

ü Divide the plotting window into subplots

ü Create three-dimensional plots

ü Use the interactive MATLAB / OCTAVE plotting tools

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 2


Amer
INTRODUCTION
Ø Large tables of data are difficult to interpret.
Engineers use graphing techniques to make the
information easier to understand.

Ø With a graph, it is easy to identify trends, pick out


highs and lows, and isolate data points that may
be measurement or calculation errors.

Ø Graphs can also be used as a quick check to


determine whether a computer solution is yielding
expected results.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 3


Amer
TWO-DIMENSIONAL PLOTS
Ø The most useful plot for engineers is the x-y
plot. A set of ordered pairs is used to identify
points on a two-dimensional graph; the
points are then connected by straight lines.
Ø The values of x and y may be measured or
calculated.
Ø Generally, the independent variable is given
the name x and is plotted on the x-axis, and
the dependent variable is given the name y
and is plotted on the y-axis.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 4


Amer
BASIC PLOTTING
Simple x–y Plots
Ø Once vectors of x-values and y-values have been defined,
MATLAB / OCTAVE makes it easy to create plots.
ØSuppose a set of time versus distance data were obtained
through measurement.
ØWe can store the time values in a vector called x (the user can
define any convenient name) and the distance values in a vector
called y :
x = [0:2:18];
y = [0, 0.33, 4.13, 6.29, 6.85, 11.19, 13.19, 13.96, 16.33, 18.17];
ØTo plot these points, use the plot command, with x and y as
arguments:
plot (x, y)
ØA graphics window automatically opens, which MATLAB /
OCTAVE calls Figure 1. The resulting plot is shown in Figure
5.1 .

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 5


Amer
BASIC PLOTTING

Figure 5.1: Simple plot of time versus


distance created in MATLAB / OCTAVE.
Titles, Labels, and Grids
Good engineering practice requires that we include axis labels and a
title in our plot. The following commands add a title, x - and y -axis
labels, and a background grid:
plot (x, y)
Xlabel ('Time, sec')
Ylabel ('Distance, ft')
grid on

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 6


Amer
BASIC PLOTTING
Ø These commands generate the plot in Figure 5.2 . As with any
MATLAB / OCTAVE commands, they could also be combined onto
one or two lines, separated by commas:
plot (x, y) , title('Laboratory Experiment 1')
xlabel ('Time, sec' ), ylabel ('Distance, ft'), grid

Figure 5.2: Adding a


grid, a title, and labels
makes a plot easier to
interpret.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 7


Amer
BASIC PLOTTING
Ø These commands generate the plot in Figure 5.2.
As with any MATLAB / OCTAVE commands, they
could also be combined onto one or two lines,
separated by commas:
plot (x, y) , title('Laboratory Experiment 1')
xlabel ('Time, sec' ), ylabel ('Distance, ft'), grid

Figure 5.2: Adding a grid,


a title, and labels makes a
plot easier to interpret.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 8


Amer
BASIC PLOTTING
Ø STRING: Characters enclosed by single quotes.
Ø You can also resize the graphics window to whatever
size is convenient for you or add it to the MATLAB /
OCTAVE desktop by selecting the docking arrow
underneath the exit icon in the upper right-hand corner
of the figure window.
Ø Create a graph before you add the title and labels. If you
specify the title and labels first, they are erased when
the plot command executes.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 9


Amer
Figure 5.3 The graphics window opens on top of the command window. You can resize it to a
convenient shape, or dock it with the MATLAB / OCTAVE desktop.
ENGR 203_Dr. Mohsin Jamil, updated by Dr. 10
Amer
BASIC PLOTTING
Creating Multiple Plots
ØWhen MATLAB / OCTAVE generate and display a graph
window, they return immediately to execute the rest of the
commands in the program.

ØWhen making a second plot, the previous graph is


overwritten. There are two possible solutions to this
problem: Use the pause command to temporarily halt the
execution of M-file program so that you can examine the
figure, or create a second figure, using the figure function.

ØThe pause command stops the program execution until


any key is pressed. If you want to pause for a specified
number of seconds, use the pause(n) command, which will
cause execution to pause for n seconds before continuing.
ENGR 203_Dr. Mohsin Jamil, updated by Dr. 11
Amer
BASIC PLOTTING
Ø The figure command opens a new figure window. The
next time a plot is made, it will be displayed in a new
window.
Ø For example, the following command;
figure(2)
opens a window named “Figure 2, ” which then becomes
the window used for subsequent plotting.
Ø Executing figure without an input parameter causes a
new window to open, numbered consecutively one up
from the current window.
Ø For example, if the current figure window is named
“Figure 2, ” executing figure will cause “Figure 3” to
open. The commands used to create a simple plot are
summarized in Table 5.1.
ENGR 203_Dr. Mohsin Jamil, updated by Dr. 12
Amer
BASIC PLOTTING

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 13


Amer
BASIC PLOTTING
Plots with More than One Line
Ø A plot with more than one line can be created in several ways. By
default, the execution of a second plot statement will erase the first
plot.
Ø However, you can layer plots on top of one another by using the hold
on command. Execute the following statements to create a plot with
both functions plotted on the same graph, as shown in Figure 5.4 :
x = 0:pi/100:2*pi;
y1 = cos(x*4);
plot(x, y1)
y2 = sin(x);
hold on;
plot(x, y2)
Ø Semicolons are optional on both the plot statement and the hold on
statement. MATLAB / OCTAVE will continue to layer the plots until
the hold off command is executed:
hold off

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 14


Amer
BASIC PLOTTING
Ø To create a graph with multiple data graphs in a single plot
command, the following syntax is used:
plot(X1, Y1, X2, Y2)
Ø where the variables X1, Y1 form an ordered set of values to be
plotted and X2, Y2 form a second ordered set of values. Using the
data from the previous example,
plot(x, y1, x, y2) produces the same graph as Figure 5.4, with one
exception: The two lines are different colours. MATLAB / OCTAVE
uses a default plotting colour (blue) for the first line drawn in a plot
command.
Ø If the plot function is called with a single matrix argument, MATLAB /
OCTAVE draws a separate line for each column of the matrix. The x-
axis is labelled with the row index vector, 1: k , where k is the
number of rows in the matrix. This produces an evenly spaced plot,
sometimes called a line plot.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 15


Amer
BASIC PLOTTING
Ø If plot is called with two arguments, one a vector and the other a
matrix, MATLAB / OCTAVE successively plots a line for each row in
the matrix. For example, we can combine y1 and y2 into a single
matrix and plot against x :
Y = [y1; y2];
plot (x, Y)
Ø This creates the same plot as Figure 5.4 , with each line a different
color. Here’s another more complicated example:
X = 0:pi/100:2*pi;
Y1 = cos(X)*2;
Y2 = cos(X)*3;
Y3 = cos(X)*4;
Y4 = cos(X)*5;
Z = [Y1; Y2; Y3; Y4];
plot(X, Y1, X, Y2, X, Y3, X, Y4)
Ø This code produces the same result ( Figure 5.5 ) as
plot(X, Z)

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 16


Amer
BASIC PLOTTING

Figure 5.5: Multiple plots on the same graph.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 17


Amer
BASIC PLOTTING
Plots of Complex Arrays
Ø If the input to the plot command is a single array of complex
numbers, MATLAB / OCTAVE plots the real component on the x -
axis and the imaginary component on the y -axis. For example,
A = [0+0i, 1+2i, 2+5i, 3+4i]
plot(A)
title('Plot of a Single Complex Array')
xlabel('Real Component')
ylabel('Imaginary Component')
returns the graph shown in Figure 5.7a.
Ø If we attempt to use two arrays of complex numbers in the plot
function, the imaginary components are ignored.
Ø The real portion of the first array is used for the x-values, and the
real portion of the second array is used for the y-values.
Ø To illustrate, first create another array called B by taking the sine of
the complex array A :

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 18


Amer
BASIC PLOTTING

Figure 5.7 (a) Complex numbers are plotted with the real component on the x-
axis and the imaginary component on the y-axis when a single array is used as
input. (b) When two complex arrays are used in the plot function, the imaginary
components are ignored.
ENGR 203_Dr. Mohsin Jamil, updated by Dr. 19
Amer
BASIC PLOTTING
B = sin(A)
returns
B = 0 3.1658 + 1.9596i 67.4789 -30.8794i 3.8537-27.0168i
and
plot(A, B)
title('Plot of Two Complex Arrays')
xlabel('Real Component of the X array')
ylabel('Real Component of the Y array')

Gives an error statement.

Warning: The imaginary parts of complex X and/or Y arguments are


ignored.
The data are still plotted, as shown in Figure 5.7 b.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 20


Amer
BASIC PLOTTING
Line, Colour, and Mark Style
• To change the appearance of a plot, select user-defined line styles
and line colours and by choosing to show the data points on the
graph with user specified mark styles. The following command
help plot returns a list of the available options. You can select solid
(the default), dashed, dotted, and dash-dot line styles, and you can
choose to show the points.
• The choices among marks include plus signs, stars, circles, and x-
marks, among others. There are seven different colour choices. (See
Table 5.2 for a complete list). The following commands illustrate the
use of line, colour, and mark styles:
x = [1:10];
y = [58.5, 63.8, 64.2, 67.3, 71.5, 88.3, 90.1, 90.6, 89.5, 90.4];
plot(x, y, ':ok')
• The resulting plot ( Figure 5.8a ) consists of a dashed line, together
with data points marked with circles. The line, the points, and the
circles are drawn in black.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 21


Amer
ENGR 203_Dr. Mohsin Jamil, updated by Dr. 22
Amer
BASIC PLOTTING

Figure 5.8 (a) Adjusting the line, mark, and colour style. (b) Multiple plots with
various line styles and point styles.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 23


Amer
BASIC PLOTTING
Ø The indicators were listed inside a string, denoted with
single quotes. The order in which they are entered is
arbitrary and does not affect the output.

Ø To specify line, mark, and colour styles for multiple


lines, add a string containing the choices after each
pair of data points. If the string is not included, the
defaults are used.
For example,
plot(x, y, ':ok', x, y*2, '--xr', x, y/2, '-b')
results in the graph shown in Figure 5.8b.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 24


Amer
BASIC PLOTTING
Axis Scaling and Annotating Plots
ØMATLAB / OCTAVE automatically selects appropriate x-axis and y-axis
scaling. Controlling the axis scaling is accomplished with the axis
function, shown in Table 5.3. Executing the axis function without any
input
axis
Øfreezes the scaling of the plot. If you use the hold on command to add
a second line to your graph, the scaling cannot change. To return control
of the scaling to MATLAB / OCTAVE, simply re-execute the axis function.
ØThe axis function also accepts input defining the x-axis and y-axis
scaling. The argument is a single matrix, with four values representing:
ØThe minimum x value shown on the x–axis The maximum x value
shown on the x–axis. The minimum y value shown on the y–axis and The
maximum y value shown on the y-axis
Thus, the command
axis([-2, 3, 0, 10])
fixes the plot axes to x from -2 to -3 and y from 0 to 10.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 25


Amer
ENGR 203_Dr. Mohsin Jamil, updated by Dr. 26
Amer
BASIC PLOTTING
Ø MATLAB / OCTAVE offers several additional functions, also listed in
Table 5.3 , that allow you to annotate your plots.
Ø The legend function requires the user to specify a legend in the form
of a string for each line plotted, and displays it in the upper right hand
corner of the plot.
Ø The text function allows you to add a text box to your plot, which is
useful for describing features on the graph.
Ø The use of both legend and text is demonstrated in the following code,
which modifies the graph from Figure 5.8b .
legend('line 1', 'line 2', 'line3')
text(1, 100, 'Label plots with the text command')
Ø We added a title, x and y labels, and adjusted the axis with the
following commands:
xlabel('My x label'), ylabel('My y label')
title('Example graph for Chapter 5'
axis([0, 11, 0, 200])
The results are shown in Figure 5.9.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 27


Amer
BASIC PLOTTING

Figure 5.9: Final version of the sample graph, annotated with a legend, a text
box, a title, x and y labels, and a modified axis.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 28


Amer
BASIC PLOTTING
Ø You can use Greek letters in your titles and labels by
putting a backslash (\) before the name of the letter. For
example,
graphics_toolkit(“gnuplot”); % This command is necessary for Octave
title('\alpha \beta \gamma‘) %creates the plot title
αβγ
Ø To make Octave use the gnuplot option for graphics, the
following line should be added to the ,octaverc startup file:
graphics_toolkit(“gnuplot”);
Ø To create a superscript, use a caret. Thus,
title('x ^2') gives
x2

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 29


Amer
BASIC PLOTTING
Ø To create a subscript, use an underscore.
title('x_5') gives
x5
Ø If your expression requires a group of characters
as either a subscript or a superscript, enclose
them in curly braces. For example,
title('k^{-1}') which returns
k-1
Ø To create a title with more than one line of text,
you’ll need to use a cell array. The syntax is:
title({'First line of text'; 'Second line of text'})

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 30


Amer
PRACTICE EXERCISES 5.1
1.Plot x versus y for y = sin(x). Let x vary from 0 to 2π in increments of
0.1π.
2. Add a title and labels to your plot.
3.Plot x versus y1 and y2 for y1 = sin(x) and y2 = cos(x). Let x vary from
0 to 2π in increments of 0.1π. Add a title and labels to your plot.
4.Re-create the plot from Exercise 3, but make the sin (x) line dashed and
red. Make the cos(x) line green and dotted.
5. Add a legend to the graph in Exercise 4.
6.Adjust the axes so that the x-axis goes from -1 to 2π + 1 and the y–axis
from -1.5 to +1.5.
7.Create a new vector, a = cos(x). Let x vary from 0 to 2π in increments of
0.1π. Plot just a without specifying the x values ( plot(a) ) and observe the
result. Compare this result with the graph produced by plotting x versus a.
ENGR 203_Dr. Mohsin Jamil, updated by Dr. 31
Amer
SUBPLOTS
Ø The subplot command allows you to subdivide the graphing window
into a grid of m rows and n columns. The function
subplot(m, n, p)
Ø splits the figure into an m×n matrix. The variable p identifies the
portion of the window where the next plot will be drawn.
Ø For example, if the command
subplot(2, 2, 1)
is used, the window is divided into two rows and two columns, and
the plot is drawn in the upper left-hand window ( Figure 5.14 ).

Figure 5.14 Subplots are used to subdivide the figure window into an m×n matrix.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 32


Amer
SUBPLOTS
Ø the following commands split the graph window into a
top plot and a bottom plot:
x = 0:pi/20:2*pi;
subplot(2, 1, 1)
plot (x, sin(x))
subplot(2, 1, 2)
plot(x, sin(2*x))
Ø The first graph is drawn in the top window, since p=1.
Then the subplot command is used again to draw the
next graph in the bottom window. Figure 5.15 shows
both graphs.
Ø Titles are added above each sub window as the graphs
are drawn, as are x and y-axis labels and any
annotation desired.
ENGR 203_Dr. Mohsin Jamil, updated by Dr. 33
Amer
SUBPLOTS

Figure 5.15 The subplot command allows the user to create multiple
graphs in the same figure window.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 34


Amer
PRACTICE EXERCISES 5.2
1.Subdivide a figure window into two rows and one
column.
2.In the top window, plot y = tan(x) for -1.5 ≤ x ≤1.5. Use an
increment of 0.1.
3. Add a title and axis labels to your graph.
4.In the bottom window, plot y = sinh(x) for the same
range.
5. Add a title and labels to your graph.
6.Try the preceding exercises again, but divide the figure
window vertically instead of horizontally.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 35


Amer
OTHER TYPES OF TWO-DIMENSIONAL PLOTS

Ø There are other ways to represent data. Depending on the situation,


these techniques may be more appropriate than an x–y plot.
Polar Plots
Ø MATLAB / OCTAVE provides plotting capability with polar
coordinates:
polar(theta, r)
Ø generates a polar plot of angle theta (in radians) and radial distance r.
For example, the code
x = 0:pi/100:pi;
y = sin(x);
polar (x, y)
Ø generates the plot in Figure 5.16 . A title was added in the usual way:
title('The sine function plotted in polar coordinates is a circle.')

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 36


Amer
Figure 5.16 A polar plot of the sine function.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 37


Amer
PRACTICE EXERCISES 5.3
1.Define an array called theta, from 0 to 2π, in steps of 0.01π. Define an
array of distances r = 5*cos(4*theta). Make a polar plot of theta versus r.
2.Use the hold on command to freeze the graph.
Assign r = 4*cos(6*theta) and plot.
3.Create a new figure. Use the theta array from the preceding
exercises. Assign r =5 -5*sin(theta) and create a new polar plot. Add a
title.
4.Create a new figure. Use the theta array from the preceding
exercises. Assign r =sqrt(5^2*cos(2*theta)) and create a new polar plot.
5.Create a new figure. Define a theta array such that theta = pi/2:4/5*pi:
4.5pi; Create a six-member array of ones called r . Create a new polar
plot of theta versus r.
See the book for the drawn polar plots

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 38


Amer
OTHER TYPES OF TWO-DIMENSIONAL PLOTS
Bar Graphs and Pie Charts
Ø Bar graphs, histograms, and pie charts are popular forms for reporting
data. Some of the commonly used MATLAB / OCTAVE functions for
creating bar graphs and pie charts are listed in Table 5.5.
Ø Examples of some of these graphs are shown in Figure 5.19. The
graphs make use of the subplot function to allow four plots in the
same figure window:
clear, clc
x = [1, 2, 5, 4, 8];
y = [x;1:5];
subplot(2, 2, 1)
bar(x), title('A bar graph of vector x')
subplot(2, 2, 2)
bar(y), title('A bar graph of matrix y')
subplot(2, 2, 3)
bar3(y), title('A three-dimensional bar graph')
subplot(2, 2, 4)
pie(x), title('A pie chart of x')
ENGR 203_Dr. Mohsin Jamil, updated by Dr. 39
Amer
ENGR 203_Dr. Mohsin Jamil, updated by Dr. 40
Amer
Figure 5.19 Sample bar and pie charts. The subplot function was used to divide
the window into quadrants.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 41


Amer
OTHER TYPES OF TWO-DIMENSIONAL PLOTS
Histograms
ØA histogram is a special type of graph particularly useful for data statistical
analysis of data. It is a plot showing distribution of a set of values.
ØIn MATLAB / OCTAVE, the histogram computes the number of values
falling into 10 bins (categories) that are equally spaced between the
minimum and maximum values. For example, if we define a matrix x as the
set of grades from the Introduction to Engineering final, the scores could be
represented in a histogram, shown in Figure 5.20 and generated with the
following code:
x = [100, 95, 74, 87, 22, 78, 34, 35, 93, 88, 86, 42, 55, 48];
hist(x)
ØThe default number of bins is 10, but if we have a large data set, we may
want to divide the data up into more bins. For example, to create a
histogram with 25 bins, the command would be
hist(x, 25)
If you set the hist function equal to a variable, as in
A = hist(x) the data used in the plot are stored in A :
A=1211101133
ENGR 203_Dr. Mohsin Jamil, updated by Dr. 42
Amer
Figure 5.20 A histogram of grade data.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 43


Amer
THREE-DIMENSIONAL PLOTTING
Ø MATLAB / OCTAVE offers a variety of three-dimensional plotting
commands, several of which are listed in Table 5.7.
Three-Dimensional Line Plot
Ø The plot3 function is similar to the plot function, except that it accepts
data in three dimensions. Instead of just providing x and y vectors, the
user must also provide a z vector. These ordered triples are then plotted
in three-space and connected with straight lines. For example,
clear, clc
x = linspace(0, 10*pi, 1000);
y = cos(x);
z = sin(x);
plot3(x, y, z)
grid
xlabel('angle'), ylabel('cos(x)'), zlabel('sin(x)'), title('A Spring')
Ø Re-create the plot shown in Figure 5.27 , but this time with the comet3
function:
comet3(x, y, z)
ENGR 203_Dr. Mohsin Jamil, updated by Dr. 44
Amer
THREE-DIMENSIONAL PLOTTING
Ø The title, labels, and grid are added to the graph in Figure 5.27 in
the usual way, with the addition of zlabel for the z -axis. The
coordinate system used with plot3 is oriented using the right-
handed coordinate system familiar to engineers.

Figure 5.27 A three-dimensional plot of a spring. MATLAB / OCTAVE uses a


coordinate system consistent with the right-hand rule.
ENGR 203_Dr. Mohsin Jamil, updated by Dr. 45
Amer
THREE-DIMENSIONAL PLOTTING

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 46


Amer
THREE-DIMENSIONAL PLOTTING
Surface Plots
ØSurface plots allow us to represent data as a surface. We will be
experimenting with two types of surface plots: mesh plots and surf plots.

Mesh Plots
ØThere are several ways to use mesh plots. They can be used to good
effect with a single two-dimensional m×n matrix. In this application, the
value in the matrix represents the z- value in the plot. The x- and y-
values are based on the matrix dimensions. Take, for example, The code
z = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10;
2, 4, 6, 8, 10, 12, 14, 16, 18, 20;
3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
mesh(z)
xlabel('x-axis')
ylabel('y-axis')
zlabel('z-axis') generates the graph in Figure 5.28 .

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 47


Amer
THREE-DIMENSIONAL PLOTTING

Figure 5.28 Simple mesh created with a single two-dimensional matrix.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 48


Amer
THREE-DIMENSIONAL PLOTTING

Ø The graph is a “mesh” created by connecting the points defined in z


into a rectilinear grid. Notice that the x -axis goes from 0 to 10 and y
goes from 1 to 3.
Ø The matrix index numbers were used for the axis values. For
example, note that z1, 5 -the value of z in row 1, column 5 is equal to 5.
This element is circled in Figure 5.28 .
Ø The mesh function can also be used with three arguments:
mesh(x, y, z) in this case, x is a list of x-coordinates, y is a list of y-
coordinates, and z is a list of z -coordinates.
x = linspace(1, 50, 10)
y = linspace(500, 1000, 3)
z = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10;
2, 4, 6, 8, 10, 12, 14, 16, 18, 20;
3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 49


Amer
THREE-DIMENSIONAL PLOTTING
Ø The x vector must have the same number of elements as the number of
columns in the z vector and the y vector must have the same number of
elements as the number of rows in the z vector. The command
mesh(x, y, z)
Ø creates the plot in Figure 5.29a . Notice that the x -axis varies from 0 to
50, with data plotted from 1 to 50. Compare this scaling with that in
Figure 5.28 , which used the z matrix index numbers for the x and y-
axes.
Surf Plots
Ø Surf plots are similar to mesh plots, but surf creates a three-
dimensional coloured surface instead of a mesh. The colours vary with
the value of z .
Ø The surf command takes the same input as mesh: either a single input
for example, surf(z), in which case it uses the row and column indices
as x and y-coordinates or three matrices.
Ø Figure 5.29(b) was generated with the same commands as those used
to generate Figure 5.29(a), except that surf replaced mesh .
surf (x, y, z)
ENGR 203_Dr. Mohsin Jamil, updated by Dr. 50
Amer
Figure 5.29 Mesh and surf plots are created with three input arguments.
ENGR 203_Dr. Mohsin Jamil, updated by Dr. 51
Amer
THREE-DIMENSIONAL PLOTTING
Ø The shading scheme for surface plots is controlled with the shading
command. The default, shown in Figure 5.29(b), is “faceted.”
Interpolated shading can create interesting effects. The plot shown in
Figure 5.29(c) was created by adding
shading interp
Ø to the previous list of commands. Flat shading without the grid is
generated when
shading flat
Ø is used, as shown in Figure 5.29d. The color scheme used in surface
plots can be controlled with the colormap function. For example,
colormap(gray)
Ø forces a gray-scale representation for surface plots. Other available
colour maps are
autumn bone hot
spring colorcube hsv
summer cool pink
winter copper prism
jet (default) flag white
ENGR 203_Dr. Mohsin Jamil, updated by Dr. 52
Amer
THREE-DIMENSIONAL PLOTTING
ØUse the help command to see a description of the various options:
help colormap
Another Example: A more complicated surface can be created by
calculating the values of Z :
x= [-2:0.2:2];
y= [-2:0.2:2];
[X, Y] = meshgrid(x, y);
Z = X.*exp(-X.^2 - Y.^2);
Ø In the preceding code, the meshgrid function is used to create the two-
dimensional matrices X and Y from the one-dimensional vectors x and
y. The values in Z are then calculated. The following code plots the
calculated values:
subplot(2, 2, 1)
mesh(X, Y, Z)
title('Mesh Plot'), xlabel('x-axis'), ylabel('y-axis'), zlabel('z-axis')
subplot(2, 2, 2)
surf(X, Y, Z)
title('Surface Plot'), xlabel('x-axis'), ylabel('y-axis'), zlabel('z-axis')
ENGR 203_Dr. Mohsin Jamil, updated by Dr. 53
Amer
THREE-DIMENSIONAL PLOTTING
subplot(2, 2, 2)
surf(X, Y, Z)
title('Surface Plot'), xlabel('x-axis'), ylabel('y-axis'), zlabel('z-axis')
ØEither the x , y vectors or the X , Y matrices can be used to define the x
and y-axes. Figure 5.30a is a mesh plot of the given function, and Figure
5.30 b is a surf plot of the same function.
ØContour plots are two-dimensional representations of three-
dimensional surfaces, much like the familiar contour maps used by many
hikers. The contour command was used to create Figure 5.30c, and the
surfc command was used to create Figure 5.30d :
subplot(2, 2, 3)
contour(X, Y, Z)
xlabel('x-axis'), ylabel('y-axis'), title('Contour Plot')
subplot(2, 2, 4)
surfc(X, Y, Z)
xlabel('x-axis'), ylabel('y-axis')
title('Combination Surface and Contour Plot')

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 54


Amer
Figure 5.30 Surface and contour plots are different ways of visualizing the same data.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 55


Amer
THREE-DIMENSIONAL PLOTTING
Pseudo Color Plots
Ø Pseudo colour plots are similar to contour plots, except that instead of
lines outlining a specific contour, a two-dimensional shaded map is
generated over a grid.
Ø MATLAB / OCTAVE includes a sample function called peaks that
generates the x, y, and z matrices of an interesting surface that looks
like a mountain range:
[x, y, z] = peaks;
Ø With the following code, we can use this surface to demonstrate the
use of pseudo colour plots, shown in Figure 5.31 :
subplot(2, 2, 1)
pcolor(x, y, z)
Ø The grid is deleted when interpolated shading is used:
subplot(2, 2, 2)
pcolor(x, y, z)
shading interp

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 56


Amer
THREE-DIMENSIONAL PLOTTING
Ø You can add contours to the image by overlaying a contour plot:
subplot(2, 2, 3)
pcolor(x, y, z)
shading interp
hold on
contour(x, y, z, 20, 'k')
Ø The number 20 specifies that 20 contour lines are drawn, and the
'k' indicates that the lines should be black.
Ø If we hadn’t specified black lines, they would have been the same
colour as the pseudo colour plot and would have disappeared into
the image. Finally, a simple contour plot was added to the figure
for comparison:
subplot(2, 2, 4)
contour(x, y, z)
Ø Additional options for using all the three-dimensional plotting
functions are included in the help window.

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 57


Amer
Figure 5.31 A variety of contour plots is available in MATLAB / OCTAVE

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 58


Amer
SAVING YOUR PLOTS
Ø Save figures from the fi le menu, using the Save As . . . option.
Ø You’ll be presented with several choices:
1. A figure can be saved in .fig file format, which is a MATLAB / OCTAVE-
specific file format. To retrieve the figure, just double-click on the file
name in the current folder. You can do the same thing programmatically
with the code
open <figurename.fig>

2. You may save the figure in a number of different standard graphics


formats, such as jpeg ( .jpg ) and enhanced metafile ( .emf ). These
versions of the figure can be inserted into other documents, such as a
Word document.

3. Select Edit from the menu bar, then select copy figure and paste the
figure into another document.

4. You can use the file menu to create an M-file that will re-create the figure.
ENGR 203_Dr. Mohsin Jamil, updated by Dr. 59
Amer
END PROBLEMS CHPATER 5

oThe included end problems of


Chapter 5 are

ü5.1 to 5.16
ü5.21 to 5.24
ü5.28 to 5.30

ENGR 203_Dr. Mohsin Jamil, updated by Dr. 60


Amer
End of chapter 5

‫ﮫﻠﻟا‬
‫ﻢﻛاﺰ‬
‫ﺟ اﺮﯿﺧ‬

.. ‫ﺔﻠﺌﺳﻷا‬
. ENGR 203_Dr. Mohsin Jamil, updated by Dr.
Amer
61

You might also like