M03 - Programming in Matlab - XXXX - CH03
M03 - Programming in Matlab - XXXX - CH03
MATLAB
Graphics and Plotting
3.1 Introduction
Graphics and plotting are not limited to a particular discipline or subject. Whether it is a budget
document, an architectural plan or a scientific report, plotting finds its application in all fields.
Yet, the ways to present facts and figures vary from case to case. Several types of plots are use-
ful in visually illustrating and emphasizing a particular aspect of the given data. Just as good
programming requires skill, good plotting requires expertise to present the data impressively.
MATLAB has a rich collection of graphics and plotting commands to suit a wide range of
applications. What may take hundreds of lines of code in any other programming language,
MATLAB can accomplish it in just a few lines. In some situations, a large number of data sam-
ples need to be shown in a single figure window. At other times, multiple subplots with different
scales need to be accommodated in a single figure. MATLAB is adaptive to all such variega-
tion. In order to enhance the features of plotting, formatting the input data or changing the plot
aesthetics is required at times. Knowledge of suitable MATLAB plotting commands can save a
lot of time and effort. Keeping all these in mind, in this chapter, basic and advanced features of
MATLAB graphics and plotting are discussed at length.
among all the plot commands in MATLAB. The simplest format of plot function for a linear
plot is:
plot (X,Y)
This command plots the elements of vector (or matrix) X on the horizontal axis, and the ele-
ments of vector (or matrix) Y on the vertical axis. Following is a simple example:
Example 3.1
Example 3.1:
Given a linear formula: Y = 3x + 7. Create an m-file for plot y
Creating a
versus x.
simple linear plot
Solution
The following code creates the desired plot:
X = 0:0.1:10;
% X takes values from 1 to 10 with increments of 0.1
Y = 3*X + 7;
% Y generates an array of values for each value of X
plot (X,Y)
% plots Y values versus their X counterparts
35
30
25
20
15
10
5
0 1 2 3 4 5 6 7 8 9 10
Figure 3.1 A simple X-Y plot. X is in horizontal axis and Y is in vertical axis
The color and point marker can be changed on a plot by adding a third parameter (in single
quotes) to the plot command. For example, to plot this function as a red, dotted line, the code
should be changed to:
X = 0:0.1:10;
Y = 3*X + 7;
plot (X,Y,‘r:’)
Note that the third argument has r standing for red color and ‘:’ for dotted lines. The new plot
is shown in Figure 3.2.
40
35
30
25
20
15
10
5
0 1 2 3 4 5 6 7 8 9 10
The third argument in the plot command consists of one to three characters which specify
a color and/or a point marker type (or a line type). A list of colors and point markers and line
styles is given in Table 3.1. Table 3.2 lists some of the important commands associated with
plotting.
Table 3.1 Various plot colors, line and marker styles, to be used with plot function
A user can select any combination of color, marker style, and line style and type it in place of
string “style” in the following command: “ ”
plot (X,Y, ‘style’)
Consider a different option for the style chosen in the following code:
>> X = 0:10;
>> Y = 3* X + 7;
>> plot (X,Y, ‘mp-.’)
This code plots a magenta (denoted by m in the argument) dash-dot line (denoted by -. in the
argument) with a pentagram marker at each data point (denoted by p in the argument), as shown
in Figure 3.3.
Similarly, the command plot (X,Y,‘bd’) in the code plots a blue diamond at each
data point but it does not draw any line. The plot(Y) plots the columns of Y versus their
indices. Y can be a vector, a matrix, or a scalar. If Y is complex, plot(Y) is equivalent to
plot(real(Y),imag(Y)).
40
35
30
25
20
15
10
5
0 1 2 3 4 5 6 7 8 9 10
Figure 3.3 X-Y plot using a marker, line style, and color
× 1010
8
7
6
5
4
3
2
1
0
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
50
45
40
35
30
25
20
15
10
0
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Figure 3.5 Modified plot of y = exp (5t -1) with the axes limited to a range
Figure 3.4 shows that the plot goes to infinity with time. The Y axis ranges from 0 to 8e10. It
is quite difficult to visualize from this plot the nature of the function for the time interval from
0 to 1 sec. One option is to rewrite the code for t = 0 to t = 1 sec. However, a better and simpler
way is to use the axis command. The axis command changes the axis of the current plot,
so that only the desirable part of the axis is displayed. The axis command is applied in the
Figure 3.4 plot as follows:
>> axis([0, 1, 0, 50])
The modified plot in Figure 3.5 depicts the nature of function within the desired range more
clearly.
The nature of the function can be seen clearly as it moves toward infinity. The axis com-
mand is entered after the plot command (or after any command that displays a figure) has been
executed. The usage of axis command is as follows:
axis([xmin, xmax, ymin, ymax]);
Here (xmin, xmax) and (ymin, ymax) specify the x and y axis ranges, respectively.
45
The function values, specified units
40
35
30
25
20
15
10
0
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Time (sec)
Following is the complete m-file that summarizes what has been discussed so far about plot
aesthetics:
add_text.m
% Learning Plot Aesthetics
T = 0:0.01:5; % take the time range of 0 to 5 sec.
Y = exp (5*T)-1; % y is a function of time t
plot (T,Y) % plots y for given time range
axis([0, 1, 0, 50])
% set the axes limits for better clarity
title(‘an exponential plot’)
% this gives a title to your plot
xlabel(‘time (sec)’)
% label for x-axis (must be a string.)
ylabel (‘the function values, specified units’) % label for y-axis
gtext(‘labeling at any location’)
% put a label anywhere within the plot
Execute the m-file in your MATLAB window after setting proper path by executing the follow-
ing command:
>> add_text
On execution, a cross hair will appear at the end, waiting for you to click at the desired location
of the text ‘labeling at any location’. When you click at any position inside the
plot, the text would be placed at that location. Instead, you can also use the text command, but
that requires specific values of x and y coordinates. Figure 3.7 shows the final plot.
An exponential plot
50
The function values, specified units
45
40
35
Labelling at any location
30
25
20
15
10
5
0
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Time (sec)
1
0.8
0.6
0.4
0.2
0
−0.2
−0.4
−0.6
−0.8
−1
0 1 2 3 4 5 6 7
1
0.8
0.6
0.4
0.2
0
−0.2
−0.4
−0.6
−0.8
−1
0 1 2 3 4 5 6 7
Figure 3.9 A cosine curve on the same figure window of sine curve
Contrary to the previous code, execution of this code will display the plots in two different
figure windows. Every time you issue the figure command, a new figure window is created
which can be used for plotting a new dataset. The figure window generated by the last figure
command becomes the current figure window. All the subsequent plot editing commands (such
as changing the axes and adding texts) are applicable to this current figure window only. For
example, the following command labels the figure depicting plot (X,Z):
>> plot (X,Y)
>> figure
>> plot (X,Z)
>> title(‘Plot of z = cos(x)’);
>> xlabel(‘angle x’);
>> ylabel(‘Z’);
Now, to label or edit the plot (X,Y) click the Figure 3.9 with the mouse button. This will convert
the desired window into current figure window.
As the presence of many figures on the MATLAB desktop could be confusing, you can close
any window using the mouse button. Alternatively, you can issue the following command:
>> close
% This command will close the window, which is
% acting as ‘current figure window’
>> close all
% closes all the open figure windows
If you simply wish to clear the plot and want to use the same figure window for another plot,
then the following command is executed:
>> clf
% clears the plot from the ‘current figure window’,
% while keeps the window open for the next plot
Y = sin(x);
Z = cos(x);
plot (X,Y,‘r’,X,Z,‘bx’)
% could be more than two plots as well
On executing the above M-file, the plot of Figure 3.10 is generated with the sine wave in solid
red line and the cosine wave in blue line with markers as x:
The syntax of this plot command should be noted carefully. There are six arguments in this
plot command. Out of these six, the first three arguments correspond to the first function to be
plotted and the rest of the three arguments correspond to the second function to be plotted. You
can add more sets of arguments to the plot command depending upon the number of functions
to be plotted. Several functions plotted in the same figure can be differentiated through colors
and point markers.
The legend function used in this code creates the legend for the plot. The basic form is:
legend ( ‘string-1’, ‘string-2’, ..., pos)
Where, string-1, string-2, and so forth are the labels associated with the plotted functions, and
pos is an integer specifying the location of the legend. For instance, 0 in the earlier case indi-
cates automatic “best” placement for the legend.
0.8
0.6
0.4
sin x
0.2 cos x
−0.2
−0.4
−0.6
−0.8
−1
0 1 2 3 4 5 6 7
You can generate an identical plot with multiple plot commands using the hold on and
hold off commands. A hold on command generates all subsequent plots in the same
figure window, without erasing the previous plot until the hold off command is issued. The
plot of Figure 3.10 can also be generated using the following m-file:
mult_plot2.m
X = linspace (0,2*pi,50); % Choose 50 samples in
% range 0 to 2*pi
Y = sin(x);
plot (X,Y,‘r’) % the figure would be created at this
% point with y versus x curve
Z = cos(X);
hold on % h
olds the figure window so as to plot the subse-
quent plots on the same set of axes
plot (X,Z,‘bx’) % z versus x curve is added to the figure
hold off % l
oses the control over current figure. Any % sub-
sequent plot
% command will create a new figure
The first method (using single plot command) is useful when the functions to be plotted are
known a priori. However, if some of the functions are to be plotted based on some conditions,
the second method is useful.
1. It plots multiple curves on the same graph. If the “style” argument is omitted, it will assume
a solid line.
2. Labeling of the graph can be accomplished using the commands: xlabel, ylabel,
title, and legend.
3. The argument for each of these commands is simply the required text within single quotes.
For example:
xlabel(‘Displacement’)
ylabel(‘Force’)
title(‘Force-Displacement Curves’)
legend(‘Plot-1’, ‘Plot-2’)
3.5 Subplotting
Sometimes plotting several functions in a single figure is not feasible due to different scales
and units of different functions. In science and engineering applications, often it is desirable to
visualize many functions together. This can be accomplished using subplot command, which
removes the necessity of plotting various disparate plots in the same figure window. The follow-
ing example illustrates the difficulty in plotting two dissimilar functions.
Example 3.2
The average yearly rainfall and production of rice in a particular Example 3.2:
Creating
state is given by the following table for seven consecutive years.
multiple plots in
the same figure
window
To visualize the trend of rainfall and its effect on rice production, it is desirable to plot
the given data in a single window. This can be accomplished using the following code:
mult_plot3.m
% m-file for rainfall and rice production data
Years = [1997 1998 1999 2000 2001 2002 2003];
rain = [64.5 72.1 68.7 67.9 68.3 62.5 67.5];
xlabel(‘Year’)
% on the x axis is year, while y-axis is common to
% both rain and production data; the following
% legend differentiates the two curves
legend(‘average rainfall (cm)’,‘crop yield (million tonnes)’,0)
The result of executing this code is shown in Figure 3.11. However, it is obvious that it
is difficult to draw any meaningful conclusion from the plot as the two variables repre-
sented on the Y-axis are different in their scales.
In such situations where multiple functions with different scales are required to be plotted in the
same figure, subplot command is useful. The subplot command allows you to separate
the figure into as many plots as required and arrange them all in one figure. The general format
of this command is as follows:
subplot(m,n,p)
It splits the figure into a matrix of m rows and n columns, thereby creating m × n subplots in one
figure window. The variable p creates a handle for the current figure/plot window. Any subsequent
plot editing commands apply to the current window. For example, subplot(2,2,1) will split
the window space in 2 × 2 partitions and the figure handle is set to the first partition (first row,
first column). Any subsequent plot command will create a plot in this partition. The subplots
are read row wise. You are also free to use or fill any of the sections first as per your convenience.
80
70
60
50
Average rainfall (cm)
40
Crop yield (million tonnes)
30
20
10
0
1997 1998 1999 2000 2001 2002 2003
Year
Example 3.3
Example 3.3:
The following MATLAB code uses subplot command for rainfall
Creating
and rice production data given in Example 3.1.
subplots
sub_plot1.m
years = [1997 1998 1999 2000 2001 2002 2003];
rain = [64.5 72.1 68.7 67.9 68.3 62.5 67.5];
crop = [4.47 4.52 4.95 5.12 5.10 4.37 5.13];
% creating subplots for rainfall and rice production data
subplot (2,1,1)
% splits the figure into a 2×1 window,
% you can access the first partition for plotting
plot (years,rain,‘r’) % plot for the rain data
xlabel(‘Years’) % x-label for the current plot
ylabel(‘average rainfall (cm)’)
% y-label for the current plot
subplot (2,1,2)
% now access the second portion of a (2,1) window
plot (years,crop,‘bx-.’) % plot for the crop data
xlabel(‘Years’) % x-label for the current plot
ylabel(‘crop yield (million tonnes)’)
% y-label for the current plot
On executing this program, you can clearly see the two plots together in the same win-
dow as shown in Figure 3.12. You can observe that it is easier to interpret and compare
the two plots and infer meaningful information from them.
Average rainfall (cm)
75
70
65
60
1997 1998 1999 2000 2001 2002 2003
Years
Copy yield (million tonnes)
5.2
5
4.8
4.6
4.4
4.2
1997 1998 1999 2000 2001 2002 2003
Years
Subplots are not limited to just two or three plots, you can have as many plots as you desire.
Example 3.4
Example 3.4: Write MATLAB code to see a sine function, a cosine function, and
Placing plots a tangent function plotted on the same figure, but not on the same
in various subplot axis.
areas
Solution
The code is given in the following m-file:
sub_plot2.m
X = linspace(0,2*pi,50);
% Choose 50 samples in range 0 to 2*pi
Y = sin(X);
Z = cos(X);
W = tan(X);
subplot(2,2,1)
% Sets the axis handle for the next plot command
plot (X,Y)
% Plot Y versus X curve at the current axis handle
subplot(2,2,2)
% Sets the axis handle for the next plot command
plot (X,Z)
% Plot Z versus X curve at the current axis handle
subplot(2,2,3)
plot (X,W)
The plot is shown in Figure 3.13. There are only three plots, though 2 × 2 partitions of 4 subplots
were created. If you do not fill all the subplots you have created, MATLAB leaves those subplots as
empty space. You could have easily created another plot using the subplot(2,2,4) command.
Subsequent plot command issued after a subplot command replaces the plot generated
by subplot command. Consider that a plot command is appended at the end of this m-file.
1 1
0.5 0.5
0 0
−0.5 −0.5
−1 −1
0 2 4 6 8 0 2 4 6 8
40
20
0
−20
−40
0 2 4 6 8
On executing the code, you will find that the tangent plot is replaced by the plot generated with
the last plot command. To overcome this problem, the figure should be cleared (using clf), or
a new figure should be specified (using figure command). To return to a certain subplot (say
n) for further editing, execute the subplot(l,m,n)command again.
An alternative method of plotting any two functions with completely distinct ranges on the same
plot is by using plotyy command. This creates two different Y-axes on both the left and right hand
sides. The left hand Y-axis is applicable to the first plot, while the right hand Y-axis is applicable to the
second plot. The two Y-axes ranges are automatically adjusted by MATLAB to suit the given data.
Example 3.5
Plot the rainfall and crop production data given in Example 3.1 Example 3.5:
using plotyy command. Using two
y-scales with
Solution “plotyy” command
Following is the MATLAB code using plotyy:
yyplot.m
% using plotyy command for data with distinct ranges
years = [1997 1998 1999 2000 2001 2002 2003];
rain = [64.5 72.1 68.7 67.9 68.3 62.5 67.5];
crop = [4.47 4.52 4.95 5.12 5.10 4.37 5.13];
plotyy(years,rain,years,crop)
% chooses left hand y-axis for average rainfall data
% and right hand y-axis for crop yield data
xlabel(‘Years’) % on common x – axis is Years
gtext(‘average rainfall (cm)’)
% to label the first curve
gtext (‘crop yield(million tonnes)’)
% label for the second curve
75 5.5
65 4.5
60 4
1997 1998 1999 2000 2001 2002 2003
Years
Figure 3.14 Using plotyy command for plotting data with distinct ranges
The resultant plot is shown in Figure 3.14. The gtext command is used here to label the figure.
Example 3.6
Example 3.6: The rough estimate of a typical household’s monthly budget is
Creating a
given in the table below. Plot a pie chart for the same and empha-
pie chart
size the second slice in the chart.
Solution
The following M-file plots a pie chart:
pie_chart.m
% A typical pie-chart
x = [5000, 8000, 2000, 5000, 1500, 2500]; % vector x
% corresponds to the given data set in the problem
labels = {‘Essentials’, ‘Luxuries’, ‘Entertainment’, ‘Children’s ...
Education’, ‘Medical Care’, ‘Savings’};
% give labels sequentially to your data within a { }
explode = [0 1 0 0 0 0];
% vector explode is set to 1, for the slice that
% you want to highlight
pie (x, explode, labels) % plot the pie chart
% for the given data
title (‘a typical Household’s monthly budget’)
% gives a title for the given chart
Children’s education
Luxuries
Entertainment
Example 3.7
Following are the marks obtained out of 50 by 70 students of a Example 3.7:
class in a certain subject: Creating a
histogram
Marks = [32, 45, 7, 38, 40, 15, 5, 26, 0, 11, 40, 2, 18, 8, 31, 4, 27,
7, 0, 15, 12, 35, 28, 46, 9, 29, 10, 34, 2, 7, 5, 17, 2, 8, 35, 30, 11,
36, 47, 19, 16, 0, 18, 16, 14, 2, 38, 41, 42, 17, 45, 28, 48, 20, 7, 21, 8, 5, 28, 13, 22, 27,
41, 40, 36, 29, 29, 31, 34, 48]
Draw a histogram with 7 bins. Analyze the total number of students falling under dif-
ferent class-intervals. Also draw an approximate plot showing how the frequency of
students varies with marks.
Solution
MATLAB provides commands to draw such a plot without analyzing the data. Here are a
few simple commands for the desired plot (assuming that the vector “marks” has already
been entered as given in the question):
histogram.m
hist (marks, 7)
% plots the histogram for the data with 7 bins
title(‘Marks Distribution in Subject ABC’)
xlabel(‘Marks Ranges’)
ylabel(‘No. of Students’)
hold on
% hold the plot to draw the frequency curve
[n, x] = hist (marks, 7)
% n gives the frequency falling under each bin and
% x is a vector containing the bin centers.
plot (x, n, ‘md--’)
% plots a dashed graph on the same plot, showing
% the frequency curve.
hold off
This code results in the following output and plot of Figure 3.16:
n=
11 13 11 5 12 11 7
x=
3.4286 10.2857 17.1429 24.0000 30.8571 37.7143 44.5714
Note that in a histogram plot, the common boundary point of two bins is always included
in the higher class. For example, the sample value 7 is included in the class 7–14 and not
in the class 0–7.
12
10
No. of students
0
0 5 10 15 20 25 30 35 40 45 50
Marks ranges
y = e5t -1
You may want to write the given equation y = e5t -1 on your plot. This is difficult because
expressing subscript or superscript letters in a plot requires special commands. Similarly, you
may want to use special symbols such as q, n, l , ←, etc. MATLAB facilitates writing complex
notations as well as selection of font sizes, types, etc., through various tools. Following are the
two primary ways of doing this:
1. Through Handle Graphics and Latex Interpreter
2. Through Graphical User Interface (GUI) available in the figure window
manipulate this object. Following are some of the important MATLAB functions on
handles:
To modify the properties of the axes of the current plot, you first need to get the handle of the
axes as shown here:
h1 = gca
% the variable name h1 gets the handle of the
% axes of the current plot
The next step is to know the properties of the axes. You can know the properties of the axes
using the get command as follows:
>> figure
% creates a new figure window
>> h1 = gca
% gets the handle to the axes
>> get(h1)
% get the list of all the properties of the
% object with handle h1
Next, you can change any of the enlisted properties such as FontName using the set command.
The format of the set command is as follows:
set(H,‘PropertyName’,PropertyValue)
This command sets the value of the specified property for the graphics object with handle H.
H can be a vector of handles, in which case set command sets the value of properties for all
the objects.
You can also set multiple property values with a single statement using the following format
of the set command:
set(H,‘PropertyName1’,PropertyValue1,‘PropertyName2’,
PropertyValue2,.............)
>> figure
>> h1 = gca;
You can also apply the set command directly in the third line on a handle obtained through
gca command as shown here:
set(gca, ‘FontSize’,12,‘FontWeight’,‘bold’)
>> t = 0:0.01:5;
% takes the time range of 0 to 5 sec.
>> y = exp (5*t)-1;
% gets y values for given time range
>> plot (t,y)
% plots y versus time t
>> set(gca, ‘XLim’, [0 1]) % sets the X-axis limit
% to [0 1] for clarity of plot
>> set(gca, ‘YLim’, [0 50])
% sets the Y-axis limits to new values
>> xlabel (‘time, sec.’, ‘FontSize’, 12,‘FontWeight’, ‘bold’)
% set x-axis label with
% defined font size and weight
>> ylabel(‘y, specified units’, ‘FontSize’, 12,‘FontWeight’,
‘bold’) % sets y-axis label with
% defined font size and weight
>> title(‘plot for y = e^{5t}-1’, ‘FontSize’, 14,‘FontAngle’,
‘italic’) % gives title to plot with
% defined font size and font
% angle, the upward arrow followed by braces { } uses
% the LaTeX interpreter, for super script letters.
30
25
20
15
10
5
0
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Time, sec
1. Set the x-axis and y-axis tic labels with font size of 10 points.
2. Write the x-label and y-label in the font-type arial with italics face.
3. Write the equation (y = e5t -1) as a label adjacent to its plot.
Example 3.9
Example 3.9: Consider the RC circuit as shown in Figure 3.18. The switch S is closed
Using handle in the beginning and the circuit is in a steady state. Switch opens at
graphics for plot time t = 0 sec. Draw the voltage across the capacitor in parallel RC
annotation
circuit as a function of time for 0 to 10 sec. Also label the response
adequately to indicate the initial voltage, time constants, and axes.
R1 = 2 Ohms
a
S
R = 2 Ohms
V(t)
V = 10 V + C = 1F
b
Solution
The natural response of the given first-order circuit is given as:
v(t) = v(0). e–t/RC
Where, n (t) is the instantaneous value of the voltage across the capacitor and v(0) is the
initial voltage (at time t = 0 sec.), which is given as:
v (0) = R.V/ (R + R1)
= 2*10/4 = 5 Volts
The value of the product RC is known as the time constant of the parallel RC circuit.
The MATLAB code for the response is as follows:
Parallel_RC.m
% m-file to plot the natural response of a given
% First-Order (RC) circuit
t = 0:0.01:10;
v_init = 5;
R = 2; C= 1;
time_const = R*C;
v = v_init * exp (- t/time_const);
% plot annotation follows:
h1 = plot (t,v,‘k’,‘LineWidth’,1);
% h1 is a handle to plot; you can access all the
% properties of the plot if you type command
% ‘get(h1)’ at MATLAB prompt. Here the line
% width of the curve is set to 1 point.
h2 = gca;
% gives us access to handle of the axes of the
% current plot.
result = get(h2)
% this will display all the available properties
%of the current axes.
set(h2,‘LineWidth’,1,‘FontSize’,12,‘FontWeight’,‘bold’)
% ‘set’ is used to change any of the properties
% of the object (axes in the present case) with
% the given handle
title (‘natural response of a first order RC circuit’,’fontsize’,
14,
‘FontAngle’, ‘italic’,‘FontName’,‘Times’)
% this could also be done by assigning a handle
% to the title and then subsequently setting its
% properties through ‘set’ command.
xlabel (‘t, sec.’, ‘fontsize’, 12,‘FontWeight’, ‘bold’)
% in a similar way you can
% change any other property
ylabel (‘v(t), volts’,‘fontsize’, 12,‘FontWeight’, ‘bold’)
text (1.5,2.5, ‘\leftarrow v(t) = v(0). e^{-t/RC}’, ‘fontsize’,
10,‘FontAngle’, ‘italic’)...
The code is saved in the file “Parallel_RC.m”. Executing the file generates the plot as
shown in Figure 3.19.
4
V(t), volts
3
V(t) = v(0). E−t/rc
Tang
2
e
t to c
1
urve
Table 3.3 Notations
Notation Interpretation
\bf Bold faced letters
\it Italics letters
\rm Removes the set properties and restores
default
_ An underscore for lowercase letters or
subscripts
^ Uppercase letters or superscripts
For a better understanding of the concepts, enter the commands in the file one by one at your
MATLAB prompt and observe the changes in the plot. Note that the tangent meets the x-axis at
a value equal to one time constant.
Note: MATLAB plots have an inbuilt LaTeX interpreter for interpreting lowercase /uppercase
/bold-face /italics letters and complex symbols. A LaTeX interpreted notation is normally pre-
ceded by a back-slash (\) symbol. Some of the commonly used notations are listed in Table 3.3.
While using the underscore ( _ ) and ^ symbols, if there is more than one character involved,
then you need to use braces ( { } ) around all the characters to be displayed in lowercase / upper-
case, otherwise only the first character will be displayed in lowercase / uppercase and all others
will be written normally. On the other hand, notations like \bf and \it will be applicable to all
the following characters in the string until you use \rm to remove these effects. In order to write
different mathematical symbols over plots, use the LaTeX interpreter.
Example 3.10
The process of carbon dating is based on many assumptions, such as: Example 3.10:
Using handle
1. The proportion of C-14 (an Isotope of carbon) to C-12 is con- graphics and
stant in the atmosphere for millions of years. latex interpreter
2. The amount of C-14 in the body at the time of death is assumed for special
to be known. symbols.
3. You can accurately measure the amount of C-14 present in the
sample.
The amount of time that has passed can be measured with the help of the following
Radio-active decay equation: Qt = Q0. e -l. t, where, Qt is the amount of radio-active C-14
present now, Q0 is the initial amount of radio-active C-14 and l is the decay constant
(0.00012097/year, for C-14).
Write a program to plot the percent of C-14 remaining as a function of time. Use handle
graphics or LaTex interpreter to annotate the plot as follows:
1. The x-axis and y-axis line width as 1 and tick label font size as 10 points.
2. The x-label and y-label in bold face letters of size 10.
3. The decay equation should be written over the plot. Indicate the half-life period of
C-14 with a marker and dotted line
Solution
The equation can be written as: t = -1/l . loge(Qt /Q0). The half-life period of C-14 is
the time required for the amount C-14 to become half of the o riginal amount, that is,
Qt = 0.5Q0. The MATLAB code for the given problem is as follows:
C_dating.m
% m-file Program for Carbon Dating
t = 0:100:10000;
lamda = 0.00012097;
q_percent = 100*exp (-lamda.*t);
plot (t,q_percent,‘LineWidth’,1)
set(gca,‘LineWidth’,1,‘Fontsize’,10)
xlabel(‘\bf\fontsize{10} Time elapsed in years’)
ylabel(‘\bf\fontsize{10} % of C-14 remaining’)
text(3000,100*exp (-lamda*3000),‘\leftarrow Q_t/Q_0 = e^{-\lambda.t}’)
hold on
plot (t,q_percent,‘LineWidth’,1)
set(gca,‘LineWidth’,1,‘Fontsize’,10)
xlabel(‘\bf\fontsize{10} Time elapsed in years’)
ylabel(‘\bf\fontsize{10} % of C-14 remaining’)
text(3000,100*exp(-lamda*3000),‘\leftarrowQ_t/Q_0 = e^{-\lambda.t}’)
hold on
half_life = -1/lamda*log(0.5)
plot (half_life, 50,‘s’,‘MarkerEdgeColor’,‘k’,...
‘MarkerFaceColor’,[.49 1 .63],‘MarkerSize’,8)
line([0 half_life],[50 50],‘LineStyle’,‘:’,‘color’, ‘k’)
line([half_life half_life],[10 50],‘LineStyle’,‘:’, ‘color’,‘k’)
text(100,48,‘\it\bf\fontname{courier}\fontsize{10} half life...
period of C-14’)...
Here you must use properties such as font size, font name, etc., in lower case only (followed
by the property values in braces, { }). However, if you use handle graphics (as in the case of
“plot” and “set” commands in Example 3.10), it does accept any variation in letter case
and there should be no gap space in property names. For example, writing “font case” or
“font name” will result in an error. Some of the important symbols and their LaTeX syntax
are given in Table 3.4.
100
90
% of C-14 remaining 80
70
← Qt /Q0 = e−lt
60
50
Half life period of C-14
40
30
20
10
0 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000
Time elapsed in years
Table 3.4 L
aTeX syntax for upper and lowercase greek letters and mathematical
symbols
Upper
Lower Case Letters Mathematical Symbols
Case Letters
Symbol Syntax
Important Notes:
1. There are syntax \psi and \Psi with only one letter case difference and these indicate
similar symbols in lower and upper cases. But the similarities like this are not always
applicable.
2. Again, there are Mathematical symbols like ← and ⇐ with their syntax with only one letter
case difference. The similar notation is applicable to other arrow marks, but not always to
all other mathematical symbols.
3. As mentioned before, to write something in subscript or superscript (/power), use under-
score (_) and ^ symbol respectively, followed by the braces { } for more than one char-
acter. The same notations are to be used if you like to write symbols and/or any text as a
subscript/superscript. For writing the bold and italic face letters refer to earlier note.
Once you enter this code, the actual plot will appear in the MATLAB figure window as shown
in Figure 3.21. Some of the main attributes of the figure window are labeled with arrow
marks.
The topmost row on the figure window of Figure 3.21 shows different pull-down menus.
Some simple tasks are discussed here.
The first step is to invoke the plot editing mode indicated by arrow in the figure window. You
can access or change the parameters of your plot only when this tool is ON. Click it with your
mouse left button and then select any of the elements of the current plot through the right but-
ton of mouse (or double click with left button). This gives you quick access to all the important
parameters of that plot element/object. For example, in the current sin-cos plots of the figure,
select the sine curve with the right mouse button after you have invoked the plot editing mode
as discussed. The display is shown in Figure 3.22.
Now, select the line-width as shown in the display and choose the desired line width from the
menu. In this way you can modify the line width. Similarly, other properties such as line style
and color can be modified. Click the “properties” in the displayed menu to access all parameters
of the line such as, the marker type, marker size, and color.”
In a similar manner, you can select the legend or the axes and make the desired changes in
the properties of these objects. This is an easier alternative as compared to obtaining the handle
of each object and then using get and set commands to set their specific properties. Moreover,
there are various short cuts in the figure tool bar. They are as follows.
The Figure Toolbar: Figure toolbar is a useful tool to access the important features of the
plot. You can invoke or deactivate the figure toolbar in your figure window using the View menu.
The figure toolbar is shown in Figure 3.23.
A short description of the numbered icons of the toolbar is as follows:
1 2 3 4 5 6 7 8 9 10 11 12
7. Zooms out or reduces the size of a magnified plot gradually to its original shape.
8. Pan tool enables or disables pan mode on a plot.
9. Rotates the plot in 3-D.
10. Data cursors enable you to read the data directly from the graph by displaying the values of
points you select on plotted lines, surfaces, images, and so on.
You can plot the sine and cosine curves again as discussed in previous examples. Go to Tools
menu on your figure tool bar with the above sine and cosine curves on the plot. You can find one
of the options as Basic Fitting. This facilitates the user to directly fit the data shown by a plot to
spline interpolation/shape-preserving interpolation or to various other curve fits ranging from
linear to tenth degree polynomial fits. An example of fourth degree polynomial fit is shown in
Figure 3.24 for the sine curve. This tool facilitates you to view the equations and plot the residuals
(or the errors in the curve fit) directly on the figure window, without any additional programming.
Apr 10.1
May 15
Jun 67.9
Jul 200.4
Aug 200.3
Sep 122.5
Oct 18.5
Nov 3
Dec 10
Yearly 706.4
Plot this data and indicate the following on your plot: minimum, maximum, mean, median,
and standard deviation.
x = t*cos(t),
y = t*sin(t),
Find the trajectory of the object’s movement for the time interval (-10 p < t < 10 p), plotting
the time against z-axis. The m-file for this problem is as follows:
plot3D1.m
%trajectory of the object with time t;
% t is along z-axis
t = -10*pi:pi/100:10*pi;
x = t.*cos(t);
% note that this is an array multiplication;
% will require a dot operator preceding *
y = t.*sin(t);
h = plot3(x,y,t);
% plots x, y and t in a 3-D space
title(‘Curve u(t) = < t*cos(t), t*sin(t), t >’)
% curve title
xlabel(‘x’)
ylabel(‘y’)
zlabel(‘time’)
grid
% sets the grid lines to the plot.
% ‘grid off’ removes them
The function plot3 has been used here. It takes three input parameters, which are arrays hold-
ing the coordinates of the points on the curve being plotted. Another new command in this code
is zlabel (see line 2 from the end), which is used to label the z-axis. The resultant plot is shown
in Figure 3.25.
The function mesh is used to plot graphs of 3-D mesh surfaces. The task is to plot a mesh sur-
face over a grid which is defined as the cartesian product of two sets. It is shown here:
>> x = [0 1 2];
>> y = [10 12 14];
40
20
Time
− 20
− 40
40
20 40
0 20
0
−20 −20
y − 40 − 40
x
The function meshgrid is useful for generating data in a form that can be supplied to the
mesh command. The meshgrid command generates two matrices for 3-D plots when applied
to the arrays x and y as follows.
>> [xi, yi] = meshgrid(x,y)
xi =
0 1 2
0 1 2
0 1 2
yi =
10 10 10
12 12 12
14 14 14
Note that the matrix xi contains replicated rows of the array x, while yi contains replicated columns
of y. The z-values of a function to be plotted are computed from arrays xi and yi. Example 3.11
illustrates the use of meshgrid command.
Example 3.11
Example 3.11: A hyperbolic paraboloid is a function of the coordinates x and y as:
Creating a
z = y2 – x2. Plot the profile of the paraboloid over the range: (–1 <
3-D plot
x < 1) and (–1 < y < 1)
The m-file program is as follows:
plot3D2.m
% m-file for the paraboloid; a ‘mesh’ plot
x = -1:0.05:1;
y = x;
[xi, yi] = meshgrid(x,y);
% this produces a multiple set of coordinates
% with all the combinations of x and y in the
% given range.
zi = yi.^2 - xi.^2;
% evaluates z for all the coordinates generated
% by meshgrid command above
mesh(xi, yi, zi)
% generates a mesh plot
colormap cool
% sets the current figures color map to certain
% pre-defined or supplied values
% (see >>help colormap for details)
axis off % the axes lines are removed
This shows the profile of the paraboloid as a mesh surface, as shown in Figure 3.26.
To plot the graph of the mesh surface together with a contour plot beneath the plotted surface
you can use function meshc in place of mesh. The arguments for meshc are the same as for
mesh.
>> meshc(xi, yi, zi)
% combination mesh/contour plot
>> colormap gray
% sets the colormap to gray
>> axis off
graph5.m
% Script file graph5.
% illustrating Surface Plot of the hyperbolic
% paraboloid
% z = y^2 - x^2, and its Level Curves.
x = -1:.05:1;
y = x;
[xi,yi] = meshgrid(x,y);
% same as in previous example
zi = yi.^2 - xi.^2;
surfc(xi,yi,zi) % creates a surface plot
colormap copper
% sets the colormap to a pre-defined map type
shading interp
% sets the color shading to a pre-defined mode
% (see >> help shading)
view([25,15,20])
% sets a particular angle view for the plot
grid off
title(‘Hyperbolic paraboloid z = y^2 – x^2’)
xlabel(‘x’); ylabel(‘y’); zlabel(‘z’)
% x, y and z labels
figure
>> graph5
This command results in the plots shown in Figure 3.28, 3.29, and 3.30:
Hyperbolic paraboloid z = y 2 − x 2
0.5
0
z
−0.5
−1
−1 −0.5
−1 0
−0.5
0 0.5
0.5
1 1 x
y
−0
0
0.2 0. −0.
. 2
30 −0
.6
−0
.6
25 0
−0.4
−0.2
0
−0.2
−0.4
Y
20
0
.6 −0.8
15
0
−0
.6
10 0.2 0.2 −0
−0
0.4 .4
−0
0.6 0 .2
−0 .4
.2
5
−0
0.
0.6 0.
4
0.8
4
8
0.
0
5 10 15 20 25 30 35 40
X
1.5
0.5
0
0
−0.5 3
−1 2.5
2
−1.5 1.5
−2 1
Several new commands are used in this file. The command surfc plots a surface together with
its level lines beneath. Unlike the command surfc, the command surf plots a surface without
the level curves. The colormap command is used to paint the surface using user-supplied colors.
If the command colormap is not given, MATLAB uses default colors. You can use >> help
colormap to see the other pre-defined colormaps in MATLAB. The view command specifies
the 3-D graph viewpoint. It takes a 3-D vector, which sets the view angle in cartesian coordinates.
In order to enhance the graph, you can use the command contourf instead of contour.
The former is used for plotting filled contour lines, which cannot be accomplished by using the
latter. The command clabel adds height labels to the current contour plot
Example 3.12
MATLAB has certain pre-defined commands for generating Example 3.12:
Generating
special surfaces. The command sphere(n) generates a unit
special surfaces
sphere with center at the origin using (n + 1) points. If func-
2
Unit cone
0.8
0.6
0.4
0.2
0
1
0.5 1
0 0.5
0
−0.5 −0.5
−1 −1
3.5
2.5
1.5
0.5
0
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
0.8
0.6
0.4
0.2
0
1
0.5 1
0 0.5
0
−0.5
−0.5
−1 −1
Example 3.13
Plot a graph of the surface of revolution obtained by rotating the Example 3.13:
Plotting the
curve r(t) = < sin(t), t >, 0 < t < pi about the y-axis.
surface of rev-
olution
Solution
The graph of generating curve and the surface of revolution are
created using the following code: The plots appear in Figures 3.32
and 3.33.
>> t = 0:pi/100:pi;
>> r = sin(t);
>> plot (r,t)
>> cylinder(r,15)
>> shading interp
Let us again take the simple exponential equation (y = e5t -1). Recall that the following code
was used previously to plot the equation and to change the axes limits:
plotp.m
t = 0:0.01:5;
y = exp (5*t)-1;
plot (t,y)
set(gca, ‘XLim’, [0 1])
set(gca, ‘YLim’, [0 50])
You can perform the same task using the following one line command:
>> fplot(‘exp (5*t)-1’, [0 1 0 50])
% note that in place of ‘t’, it could be x or y
% or any other single variable as well.
Here, “fplot” is a function plotter command, with the general syntax as follows:
fplot(‘function’,LIMS)
% plots the function FUN between the x-axis.
% limits specified by LIMS = [xmin xmax].
% Use of LIMS = [xmin xmax ymin ymax] also
% controls the y-axis limits. The function must
% be supplied within the quotes.
The command “fplot” calls an inbuilt m-file program for plotting functions. Type the following
code at your MATLAB prompt and observe the display:
>> edit fplot
or
>> type fplot
It will display the contents of file “fplot.m”. You can also edit this program as per your
requirements.
The problem with the fplot command is that it is a linear function taking only one variable.
Suppose, there is function in x and y as x2 + y2 - 4*x*y + 1/5 = 0. It would be very difficult to
plot such a function in the form y = f(x) using the fplot command. In order to see the depend-
ency of y over x for the range {-3 < x < 3 }, type the following code at MATLAB prompt:
>> ezplot(‘x^2 + y^2 - 4*x*y + 1/5’,[-3,3])
It results in the plot shown in Figure 3.34.
ezplot is another function plotter, which not only plots a single or two-variable expression for
the given variable ranges but also automatically labels the axes and gives a title to the plot. Note
that ezplot is another in-built m-file of MATLAB’s library functions. Type edit ezplot to
see the details of the file. Some of the common ways to use the ezplot command are:
ezplot(f)
% plots the expression f = f(x) over the default
x 2 + y 2 − 4xy + 1/5 = 0
3
0
y
−1
−2
−3
−3 −2 −1 0 1 2 3
x
SUMMARY
In this chapter, various 2-D and 3-D plot types with corresponding MATLAB graphics
commands and plotting tools were discussed. A good graph must always be properly
scaled and labeled adequately. MATLAB has more than one method of labeling the plots.
The most efficient approach is to use the “figure toolbar”. Mathematical symbols and other
symbolic representations require LaTeX interpreter. Once you have access to a particular
text object, you can type the LaTeX interpreted code in the object window as well. In case
of multiple plots, it is a good practice to use distinctly different line sizes, color or marker
types for different curves. Legend and grid features of MATLAB add clarity to your
plots.
Exercises
3.1. Roots of polynomials appear in many engineering applications. Find the real root of the
polynomial equation:
4x5 + 3x4 – 95x3 + 5x2 –10x + 80 = 0
in the range –10 ≤ x ≤ 10 by plotting the polynomial.
3.2. Trigonometric identities can be used to simplify the equations that appear in engineering
applications. Confirm the identity tan(2x) = (2 × tan x)/(1– tan2 x) by plotting both sides
of this expression for the interval 0 ≤ x ≤ 2 p.
3.3. Obtain graphically an approximate value of the roots of the following equation:
x = sin(x) + p /2
3.4. Solve the following set of equations graphically:
y = - 0.5*x + 2
y + 1 = 4*(x + 3)
3.5. The following table shows average temperature of Visakhapatnam city for five consecu-
tive years. Plot the data as a stem plot, a bar plot and a stairs plot, with suitable scaling
and labels.
3.6. Create a polar plot for the function y(t) = 10 e(-0.2 + jp)t, for 0 ≤ t ≤ 10.
3.7. The spiral of Archimedes is a curve described in polar coordinates by the equation
r = kq , where r and q are the radial distance and angular position of the point respec-
tively, corresponding to the origin. Plot the spiral of Archimedes for 0 ≤ q ≤ 6p when
k = 0.75. Label your plot appropriately.
3.8. A complex function f(t) is defined by the equation: f (t) = (3 - 2.5 j) t - 5.5.
Plot the amplitude and phase of the function as subplot for 0 ≤ t ≤ 5.
3.9. The table given here contains data for the production of red sea bream (Sparus aurata) in
Japan. Fit the given data to an exponential, third, and fourth degree polynomials. Write
the exact expression for each case and also plot the residuals for each of these curves.
(Hint: use “Data Statistics” option in Tools menu on your figure toolbar)
3.10. The height h(t) and horizontal distance s(t) traveled by a ball thrown at an angle q, with
initial speed u, is given as:
1
h(t) = u.t. sin(q ) – g.t2
2
s(t) = u.t. cos(q )
The acceleration due to gravity is g = 9.81 m/sec.2
(a) Suppose the ball is thrown with a velocity u = 10 m/sec.2 at an angle of 35°. Use
MATLAB to compute how high the ball will go, how far will it go, and how long will
it take to hit the ground?
(b) Use the values of u and q in part (a) above, to plot the ball’s trajectory, that is, plot h
versus s for all positive values of h.
(c) Plot the trajectories for the same value of u, but with different angles q : 20°, 30°,
45°, 60°, and 70°. Now find out for what angle the ball travels the highest? Mark this
trajectory with bold faced line in your plot.
(d) When a satellite orbits the earth, the satellite’s orbit forms an ellipse with earth
located at one of the focal points of the ellipse. The satellite’s orbit can be expressed
in terms of polar coordinates as:
r = z / (1 - e cos q )
where, r and q are the distance and angle of the satellite from the center of the earth, z is
a parameter specifying the size of the orbit, and e is the eccentricity of the orbit.
A circular orbit has an eccentricity e equal to 0, whereas an elliptical orbit has an
eccentricity between 0 ≤ e ≤ 1. If e > 1, the satellite follows a hyperbolic path and escapes
from the earth’s gravitational field.
Consider a satellite with a size parameter z = 1000 km. Plot the orbit of the satellite if
(a) e = 0 (b) e = 0.25 and (c) e = 0.5. What is the closest distance of each of these orbits
from earth? And how far is the farthest point on the orbit? Compare the result of all the
three plots. What is the significance of the parameter z?
3.11. The boiling point of a liquid is the temperature at which the vapor pressure of a liquid
equals the external pressure acting on its surface. For this reason, the water boils at lower
temperature at higher altitudes. This is an important concept for chemical, nuclear, and
other engineers engaged in processes dealing with boiling liquids. Data on the vapor
pressure P of water as a function of temperature T is given in the following table. Theo-
retically, the pressure P is inversely proportional to the absolute temperature T. Obtain a
curve fit for p(T) for the given data and use this fit to estimate the vapor pressure at 285 K
and 300 K.
3.12. The parametric equations of an ellipse are given by the following relations:
x = a cos(t )
y = b sin(t );0 ≤ t ≤ 2p
That is, (x2/a2) + (y2/b2) = 1; where a and b are known as semi-major axis and semi-minor
axis respectively. The eccentricity of the curve is given by the relation:
b2
e = 1−
a2
For a = 2, and b = 1.
(a) Plot the curve and mark the major axis, minor axis, and the center of the ellipse.
(b) The two foci are the points on the major axis located at a distance a × e on either side
of the center. Mark the two foci on your curve and extract their coordinates.
(c) Prove, by taking at least five points, the sum of radial distances of any point on the
curve from the two foci always remains the same. What is the numerical value of this
distance?
(d) Show graphically that circle is a special case of ellipse. What is the condition for
this?
On 3-D plots: