You are on page 1of 20

1

Lecture 7: MATLAB Graphics

Lecture 7: MATLAB Graphics


7.1 Two-Dimensional Graphics:
MATLAB has extensive facilities for displaying vectors and matrices as graphs,
as well as annotating and printing these graphs. This section describes a few of the
most important graphics functions and provides examples of some typical applications.
7.1.1 Creating a Simple 2D Plot:
In 2D plot, the basic MATLAB graphing procedure is as follows:
1) take a vector of x-coordinates, x = (x1, … , xN), and a vector of y-coordinates,
y = (y1, … ,yN).
2) locate the points (xi, yi), with i = 1, 2, … , n.
3) join the resulted points by straight lines.
Thus, we need to prepare x and y with the same length.
The MATLAB command to plot a graph is plot(x , y).
We can use the colon operator to create a vector of x values ranging from zero
to 2π, and we can compute the sine of these values to create a vector of y values ranging
from -1 to 1, and plot the result.
>> x = 0:pi/100:2*pi;
>> y = sin(x);
>> plot(x,y)

0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1
0 1 2 3 4 5 6 7

Programming II 2nd Year Rasha Hassan


2
Lecture 7: MATLAB Graphics

7.1.2 Adding Annotations:


MATLAB enables you to add axis labels, grid and titles as in Table below.
Annotation Description
legend Graph legend for lines and patches.
>> legend('fun1','fun2') plots a legend box (move it with your mouse) to name
your functions.
>> Legend off deletes the legend box.

>> title('text') Titles for 2-D and 3-D plots.


>> xlabel('text’) X-axis labels for 2-D and 3-D plots.
>> ylabel('text') Y-axis labels for 2-D and 3-D plots.
>> zlabel('text') Z-axis labels for 3-D plots.

For example, using the graph from the previous example, add an x- and y-axis
labels. Now label the axis and add a title. The character \pi creates the symbol π.
x=0:pi/100:2*pi; sine function
1
y= sin(x);
0.8

plot(x,y) 0.6

title('sine function') 0.4

xlabel('x=0:2\pi') 0.2
y=sin(x)

0
ylabel('y=sin(x)')
-0.2

-0.4

-0.6

-0.8

-1
0 1 2 3 4 5 6 7
x=0:2

7.1.3 Specifying Line Styles, Colors, and Markers:


The color of a single curve is, by default, blue, but other colors are possible. The
line styles, colors, and markers (e.g., circles, plus signs, …) can be specified using the
plot command:

Programming II 2nd Year Rasha Hassan


3
Lecture 7: MATLAB Graphics

>> plot (x,y,'style_color_marker')


Another colors and line styles can be used, see Table below.
Symbol Line Style Symbol Color Symbol Marker
k Black ‐ Solid + Plus sign
r Red ‐‐ Dashed o Circle
b Blue : Dotted * Asterisk
g Green ‐. Dash-dot . Point
c Cyan none No line x Cross
m Magenta s Square
y Yellow d Diamond
v Triangle (down)
> Triangle (left)
p Pentagram
h Hexagram

7.1.4 Setting Axis Limits:


By default, MATLAB finds the maxima and minima of the data to choose the
axis limits to span this range. The axis command enables you to specify your own
limits:
>> axis([xmin xmax ymin ymax])
or for three-dimensional graphs:
>> axis([xmin xmax ymin ymax zmin zmax])
Use the command:
>> axis auto
to re-enable MATLAB’s automatic limit selection.
7.1.5 Setting Axis Visibility:
You can use the axis command to make the axis visible or invisible.
>> axis on
makes the axis visible. This is the default.
>> axis off
makes the axis invisible.

Programming II 2nd Year Rasha Hassan


4
Lecture 7: MATLAB Graphics

7.1.6 Setting Grid Lines:


The grid command toggles grid lines on and off. The statement:
>> grid on
turns the grid lines on and
>> grid off
turns them back off again.
Example 1: Write a MATLAB program to plot the function cos(t) in the
interval of t from -2π to 2π in step of π/10. Use an asterisk marker, a magenta
color, a dash-dotted line style. Then, add a title, x-axis label, and y-axis label
to this plot. Then after, turn on the grid.
Solution:
t=-2*pi:pi/10:2*pi;
y= cos(t);
plot(t,y,'* m -.')
title('cos(t) function')
xlabel('x=-2\pi:2\pi')
ylabel('y=cos(t)')
grid on

Programming II 2nd Year Rasha Hassan


5
Lecture 7: MATLAB Graphics

7.1.7 Multiple Data Sets in One Graph:


A. Multiple x-y Pair Arguments:
Multiple x-y pair arguments create multiple graphs with a single call to plot.
MATLAB automatically cycles through a predefined (but user settable) list of colors
to allow discrimination between each set of data. For example, these statements plot
three related functions of x, each curve in a separate distinguishing color.
x=0:pi/100:2*pi; 1

y=sin(x); 0.8

0.6
y2=sin(x-0.25);
0.4

y3=sin(x-0.5); 0.2

plot(x,y,x,y2,x,y3) 0

-0.2

-0.4

-0.6

-0.8

-1
0 1 2 3 4 5 6 7

The legend command provides an easy way to identify the individual plots.
legend('sin(x)','sin(x-0.25)','sin(x-0.5)')
1
sin(x)
0.8 sin(x-0.25)
sin(x-0.5)
0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1
0 1 2 3 4 5 6 7

By default, MATLAB uses line style and color to distinguish the data sets
plotted in the graph. However, you can change the appearance of these graphic
components or add annotations to the graph to help explain your data for presentation.
Programming II 2nd Year Rasha Hassan
6
Lecture 7: MATLAB Graphics

Example 2: Write a MATLAB program to plot three functions of x in one plot, where
the first function is (2cos(x)), the second function is (cos(x)), and the third function is
(0.5 cos(x)), with the interval of 𝟎 ≤ 𝐱 ≤ 𝟐𝛑 in step of π/100. Use a dashed, a solid,
and a dotted line styles to plot these functions Then, add a title, x-axis label, y-axis
label, and legend to this plot. Then after, set the minimum and maximum values of the
axes.
Solution:
x = 0:pi/100:2*pi;
y1 = 2*cos(x);
y2 = cos(x);
y3 = 0.5*cos(x);
plot (x, y1, '--', x, y2, '-', x, y3, ':')
xlabel('0 \leq x \leq 2\pi')
ylabel('Cosine Functions')
legend('2*cos(x)','cos(x)','0.5*cos(x)')
title('Three Functions Plot')
axis([0 2*pi -3 3])
Three Functions Plot
3
2*cos(x)
cos(x)
2 0.5*cos(x)

1
Cosine Functions

-1

-2

-3
0 1 2 3 4 5 6
0  x  2

B. The Hold Command:


The hold command enables you to add plots to an existing graph. When you type
>> hold on
Programming II 2nd Year Rasha Hassan
7
Lecture 7: MATLAB Graphics

MATLAB does not replace the existing graph when you issue another plotting
command; it adds the new data to the current graph, rescaling the axes if necessary.
For example, these statements first create a contour plot of the peaks function, then
superimpose a pseudocolor plot of the same function.
x = 0:pi/100:2*pi;
y = 0:pi/10:2*pi;
plot(x,sin(x))
hold on
plot(y,cos(y))
hold off
The hold on command causes the sin(x) plot to be combined with the cos(y) plot
in one figure.

0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1
0 1 2 3 4 5 6 7

Example 3: The position 𝑥 as a function of time of a particle that moves along a straight
line is given y:
𝒙(𝒕) = 𝟎. 𝟒𝟏 𝒕𝟒 − 𝟏𝟎. 𝟖 𝒕𝟑 + 𝟔𝟒 𝒕𝟐 − 𝟖. 𝟐 𝒕 + 𝟒. 𝟒 𝒇𝒕
The velocity 𝑣(𝑡) of the particle is determined by the derivative of 𝑥(𝑡) with respect
to 𝑡, and the acceleration 𝑎(𝑡) is determined by the derivative of 𝑣(𝑡) with respect to
𝑡.

Programming II 2nd Year Rasha Hassan


8
Lecture 7: MATLAB Graphics

Derive the expression for the velocity ad acceleration of the particle, and make plots of
the position, velocity, and acceleration as function of time for 0 ≤ 𝑡 ≤ 8 𝑠. Use the
hold command to make the three plots in one plot. Label the axes appropriately with
the correct units.
Solution:
𝒗(𝒕) = 𝟏. 𝟔𝟒 𝒕𝟑 − 𝟑𝟐. 𝟒𝒕𝟐 + 𝟏𝟐𝟖 𝒕 − 𝟖. 𝟐 𝒇𝒕/𝒔
𝒂(𝒕) = 𝟒. 𝟗𝟐 𝒕𝟐 − 𝟔𝟒. 𝟖 𝒕 + 𝟏𝟐𝟖 𝒇𝒕/𝒔𝟐
MATLAB Code:
t=linspace(0,8,500);
x=0.41*t.^4-10.8*t.^3+64*t.^2-8.2*t+4.4;
v=1.64*t.^3-32.4*t.^2+128*t-8.2;
a=4.92*t.^2-64.8*t+128;
plot(t,x)
hold on
xlabel('t(s)')
ylabel('x(ft)')
plot(t,v)
hold on
xlabel('t(s)')
ylabel('v(ft.s)')
plot(t,a)
hold off
xlabel('t(s)')
ylabel('a(ft.s.^2)')
500

400

300

200
a(ft.s.2)

100

-100

-200

-300
0 1 2 3 4 5 6 7 8
t(s)

Programming II 2nd Year Rasha Hassan


9
Lecture 7: MATLAB Graphics

7.1.8 Multiple Data Sets in Multiple Graphics:


It is also possible to produce a few subplots in on figure window. With the
command subplot, the window can be horizontally and vertically divided into p×r
subfigures, which are counted from 1 to p×r, row-wise, starting from the top left. The
commands: plot, title, grid etc. work only in the current subfigure.
>> subplot(m,n,p) % To break up the plotting window into m plots in
the vertical direction (no. of rows) and n plot in the
horizontal direction (no. of columns), choosing the
pth plot for drawing into.

Example 4: Write a program to plot two functions of x in separate plots, where the
first function is (𝒆−𝟏.𝟓𝒙 𝒔𝒊𝒏(𝟏𝟎𝒙)), and the second function is (𝒆−𝟐𝒙 𝒔𝒊𝒏(𝟏𝟎𝒙)), with
the interval of t from 0 to 5 in step of 0.01. Use a square marker, a red color, a dash-
dotted line style to the first plot, and an asterisk marker, a blue color, a dotted line style
to the second plot. Then, add a title, x-axis label, and y-axis label to each plot. Then
after, turn the grid on.
Solution:
x=0:0.01:5;
y1=exp(-1.5*x).*sin(10*x);
y2=exp(-2*x).*sin(10*x);
subplot(1,2,1)
plot(x,y1,'s r -.')
title('e(-1.5x)sin(10x)')

Programming II 2nd Year Rasha Hassan


10
Lecture 7: MATLAB Graphics

xlabel('x')
ylabel('y1')
grid on
subplot(1,2,2)
plot(x,y2,'* b :')
title('e(-
2x)sin(10x)')
xlabel('x')
ylabel('y2')
grid on

If you want to clear one of the plots in a subplot without affecting the others,
you can use the cla (clear axes) command. Continuing the previous example:
subplot(1,2,1)
cla
e(-1.5x)sin(10x) e(-2x)sin(10x)
1 1

0.9
0.8
0.8

0.7 0.6

0.6
0.4
y1

y2

0.5
0.2
0.4

0.3 0

0.2
-0.2
0.1

0 -0.4
0 0.5 1 0 2 4 6
x x

7.2 Three-Dimensional Graphics:


MATLAB has a variety of functions for displaying and visualizing data in 3-D,
either as lines in 3-D, or as various types of surfaces. This lecture provides a brief
overview.

Programming II 2nd Year Rasha Hassan


11
Lecture 7: MATLAB Graphics

7.2.1 Line Plots:


A three-dimensional line plot is a line that is obtained by connecting points in
three-dimensional space. A basic 3-D plot ‘is created with the plot3 command, which
is very similar to the plot command and has the form:

❖ The three vectors with the coordinates of the data points must have the same
number of elements.
❖ The line specifiers, properties, and property values are the same as in 2-D plots
(see Section 5.1).
For example, if the coordinates x, y, and z are given as a function of the
parameter t by:
𝑥 = √𝑡 sin 2𝑡
𝑦 = √𝑡 cos 2𝑡
𝑧 = 0.5 𝑡
a plot of the points for 0 ≤ 𝑡 ≤ 6𝜋 can be produced by the following script file:
t=0:0.1:6*pi;
x=sqrt(t).*sin(2*t);
y=sqrt(t).*cos(2*t);
z=0.5*t;
plot3(x,y,z,'k','linewidth',1)
grid on
xlabel('x'); ylabel('y'); zlabel('z')
The plot shown in Figure below is created when the script is executed.

Programming II 2nd Year Rasha Hassan


12
Lecture 7: MATLAB Graphics

10

6
z

0
5
5
0
0

y -5 -5
x

7.2.2 Mesh and Surface Plots:


Mesh and surface plots are three-dimensional plots used for plotting functions
of the form 𝑧 = 𝑓(𝑥, 𝑦) where 𝑥 and 𝑦 are the independent variables and 𝑧 is the
dependent variable. It means that within a given domain the value of 𝑧 can be calculated
for any combination of 𝑥 and 𝑦.
Mesh and surface plots are created in three steps:
❖ The first step is to create a grid in the 𝑥 𝑦 plane that covers the domain of the
function.
❖ The second step is to calculate the value of 𝑧 at each point of the grid.
❖ The third step is to create the plot.
The three steps are explained next.
A. Creating a Grid in the x y Plane (Cartesian Coordinates):
The grid is a set of points in the 𝑥 𝑦 plane in the domain of the function. The
density of the grid (number of points used to define the domain) is defined by the user.
Figure below shows a grid in the domain −1 ≤ 𝑥 ≤ 3 and 1 ≤ 𝑦 ≤ 4.

Programming II 2nd Year Rasha Hassan


13
Lecture 7: MATLAB Graphics

In this grid, the distance between the points is one unit. The points of the grid
can be defined by two matrices, 𝑋 and 𝑌. Matrix 𝑋 has the 𝑥 coordinates of all the
points, and matrix 𝑌 has the 𝑦 coordinates of all the points:
−1 0 1 2 3 4 4 4 4 4
−1 0 1 2 3 3 3 3 3 3
𝑋=[ ] and 𝑌 = [ ]
−1 0 1 2 3 2 2 2 2 2
−1 0 1 2 3 1 1 1 1 1
The X matrix is made of identical rows since in each row of the grid the points
have the same x coordinate. In the same way the Y matrix is made of identical columns
since in each column of the grid the y coordinate of the points is the same.
MATLAB has a built-in function, called meshgrid, that can be used for creating
the X and Y matrices. The form of the meshgrid function is:

In the vectors 𝑥 and 𝑦 the first and last elements are the respective boundaries of
the domain. The density of the grid is determined by the number of elements in the
vectors. For example, the mesh matrices 𝑋 and 𝑌 that correspond to the grid in Figure
above can be created with the meshgrid command by:

Programming II 2nd Year Rasha Hassan


14
Lecture 7: MATLAB Graphics

>> x=-1:3;
>> y=1:4;
>> [X,Y]=meshgrid(x,y)
OR >> [X,Y]=meshgrid(-1:3,1:4)
X=
-1 0 1 2 3
-1 0 1 2 3
-1 0 1 2 3
-1 0 1 2 3
Y=
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
Once the grid matrices exist, they can be used for calculating the value of 𝑧 at
each grid point.
B. Calculating the Value of 𝒛 at Each Point of the Grid:
The value of 𝑧 at each point is calculated by using element-by-element
calculations in the same way it is used with vectors. When the independent variables 𝑥
and 𝑦 are matrices (they must be of the same size), the calculated dependent variable
is also a matrix of the same size. The value of 𝑧 at each address is calculated from the
corresponding values of 𝑥 and 𝑦. For example, if 𝑧 is given by:
𝑥𝑦 2
𝑧= 2
𝑥 + 𝑦2
the value of 𝑧 at each point of the grid above is calculated by:
>> Z = X.*Y.^2./(X.^2 + Y.^2)
Z=
-0.5000 0 0.5000 0.4000 0.3000
-0.8000 0 0.8000 1.0000 0.9231
-0.9000 0 0.9000 1.3846 1.5000
-0.9412 0 0.9412 1.6000 1.9200
Once the three matrices have been created, they can be used to plot mesh or
surface plots.

Programming II 2nd Year Rasha Hassan


15
Lecture 7: MATLAB Graphics

C. Making Mesh and Surface Plots:


A mesh or surface plot is created with the mesh or surf command, which has
the form:

where 𝑋 and 𝑌 are matrices with the coordinates of the grid and 𝑍 is a matrix
with the value of 𝑧 at the grid points. The mesh plot is made of lines that connect the
points. In the surface plot, areas within the mesh lines are colored.
As an example, the following script file contains a complete program that creates
𝑥𝑦 2
the grid and then makes a mesh (or surface) plot of the function 𝑧 = over the
𝑥 2 +𝑦 2

domain −1 ≤ 𝑥 ≤ 3 and 1 ≤ 𝑦 ≤ 4.
x=-1:0.1:3;
y=1:0.1:4;
[X,Y]=meshgrid(x,y);
Z=X.*Y.^2./(X.^2+Y.^2);
mesh(X,Y,Z)
xlabel('x'); ylabel('y'); zlabel('z')

1.5

0.5
z

-0.5

-1
4
3
3
2
2 1
0
y 1 -1
x

x=-1:0.1:3;
y=1:0.1:4;

Programming II 2nd Year Rasha Hassan


16
Lecture 7: MATLAB Graphics

[X,Y]=meshgrid(x,y);
Z=X.*Y.^2./(X.^2+Y.^2);
surf(X,Y,Z)
xlabel('x'); ylabel('y'); zlabel('z')

1.5

0.5
z

-0.5

-1
4
3
3
2
2 1
0
y 1 -1
x

7.2.3 Polar Coordinates Grid in the x y Plane:


A 3-D plot of a function in which the value of z is given in polar coordinates (for
example 𝑧 = 𝑟𝜃) can be done by following these steps:
❖ Create a grid of values of 𝜃 and 𝑟 with the meshgrid function.
❖ Calculate the value of 𝑧 at each point of the grid.
❖ Convert the polar coordinates grid to a grid in Cartesian coordinates. This can
be done with MATLAB’s built-in function pol2cart (see example below).
❖ Make a 3-D plot using the values of z and the Cartesian coordinates. For
example, the following script creates a plot of the function 𝑧 = 𝑟𝜃 over the
domain 0 ≤ 𝜃 ≤ 360° and 0 ≤ 𝑟 ≤ 2.
[th,r]=meshgrid((0:5:360)*pi/180,0:.1:2);
Z=r.*th;
[X,Y] = pol2cart(th,r);
mesh(X,Y,Z)

Programming II 2nd Year Rasha Hassan


17
Lecture 7: MATLAB Graphics

15

10

0
2
1 2
0 1
0
-1 -1
-2 -2

Example 5: Write a program to plot an inverted cone given by the function 𝒛 =


√𝒙𝟐 + 𝒚𝟐 as a 3D surface plot where r is in the interval from 0 to 10 in step of 0.5,
𝝅
and 𝜽 is in the interval from 0 to 𝟐𝝅 in step of .
𝟐𝟎

Solution: MATLAB Code:


[r,th] = meshgrid (0:0.5:10,0:pi/20:2*pi);
[x,y] = pol2cart (th,r);
z=sqrt(x.^2 + y.^2)
surf(x,y,z)
Output:

Programming II 2nd Year Rasha Hassan


18
Lecture 7: MATLAB Graphics

Example 6: Write a program to plot a 3D sinc function where x and y are in the interval
from -8 to 8 in step of 0.5.
Solution: MATLAB Code:
[x,y]=meshgrid(-8:0.5:8);
R=sqrt(x.^2+ y.^2)+eps;
z=sin(R)./R;
mesh(x , y , z )
Output:

Example 7: Write a program to plot an inverted cone given by the function 𝒛 =


√𝒙𝟐 + 𝒚𝟐 as a 3D plot without surface where r is in the interval from 0 to 10 in step
𝝅
of 0.5, and 𝜽 is in the interval from 0 to 𝟐𝝅 in step of .
𝟐𝟎

Solution: MATLAB Code:


[r,th] = meshgrid (0:0.5:10,0:pi/20:2*pi);
[x,y] = pol2cart (th,r);
z=sqrt(x.^2 + y.^2)
plot(x,y,z)
Output:

Programming II 2nd Year Rasha Hassan


19
Lecture 7: MATLAB Graphics

7.2.4 Colored Surface Plots:


A surface plot is similar to a mesh plot except the rectangular faces of the surface
are colored. The color of the faces is determined by the values of 𝑍 and the colormap
(a colormap is an ordered list of colors). These statements graph the cylinder function
as a surface plot, select a colormap, and add a color bar to show the mapping of data to
color.
Example 8: Write a program to plot a 3D cylinder function where r(t)=1+cos(t) and t
𝝅
is in the interval from 0 to 𝟐𝝅 in step of . Then, show the mapping of data to color.
𝟏𝟎

Solution: MATLAB Code:


t=0:pi/10:2*pi;
[X,Y,Z]=cylinder(1+cos(t));
surf(X,Y,Z)
colormap hsv
colorbar
Output:

Programming II 2nd Year Rasha Hassan


20
Lecture 7: MATLAB Graphics

Homework:
1. Make two separate plots of the function 𝑓(𝑡) = (𝑥 + 1)(𝑥 − 2)(2𝑥 − 0.25) −
𝑒 𝑥 , one plot for 0 ≤ 𝑥 ≤ 3 and one for −3 ≤ 𝑥 ≤ 6.
2. The position 𝑥 as a function of time of a particle that moves along a straight line
is given y:
𝒙(𝒕) = 𝟎. 𝟒𝟏 𝒕𝟒 − 𝟏𝟎. 𝟖 𝒕𝟑 + 𝟔𝟒 𝒕𝟐 − 𝟖. 𝟐 𝒕 + 𝟒. 𝟒 𝒇𝒕
The velocity 𝑣(𝑡) of the particle is determined by the derivative of 𝑥(𝑡) with respect
to 𝑡, and the acceleration 𝑎(𝑡) is determined by the derivative of 𝑣(𝑡) with respect to
𝑡.
Derive the expression for the velocity ad acceleration of the particle, and make plots of
the position, velocity, and acceleration as function of time for 0 ≤ 𝑡 ≤ 8 𝑠. Use the
subplot command to make the three plots on the same page with the plot of the
position on the top, the velocity in the middle, and the acceleration at the bottom. Label
the axes appropriately with the correct units.
3. Write a MATLAB program to plot four curves of isotherms in one plot for one
mole of an ideal gas for volume ranging from 1 to 10 𝑚3 , at temperatures of
𝑇 == 100, 200, 300, 𝑎𝑑 400 𝐾, respectively. Label the axes and display a
legend. The units for pressure are Pa. If the ideal gas law relates the pressure 𝑃,
volume 𝑉, and temperature 𝑇 of an ideal gas:
𝑃𝑉 =nRT
where 𝑛 is the number of moles and 𝑅 = 8.3145 𝐽(𝐾 𝑚𝑜𝑙).
Hint: plot of pressure versus volume at constant temperature are called isotherms.

Programming II 2nd Year Rasha Hassan

You might also like