Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
28 views

M03 - Programming in Matlab - XXXX - CH03

The document discusses MATLAB graphics and plotting capabilities. It introduces basic 2D plotting in MATLAB using the plot command and describes how to customize plots by changing colors, markers, and line styles. Examples are provided to demonstrate simple linear plotting and practicing different plot styles.

Uploaded by

Insignia D.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

M03 - Programming in Matlab - XXXX - CH03

The document discusses MATLAB graphics and plotting capabilities. It introduces basic 2D plotting in MATLAB using the plot command and describes how to customize plots by changing colors, markers, and line styles. Examples are provided to demonstrate simple linear plotting and practicing different plot styles.

Uploaded by

Insignia D.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

3

MATLAB
Graphics and Plotting

After studying this chapter, you should be able to:


 use basic features of MATLAB  learn 2-D and 3-D plotting and plot
graphics annotation
 learn simple and multiple plots and  plot various simple and complex
subplots functions

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.

3.2 2-Dimensional Plots


One of the most important functions in MATLAB is the plot function. It is also one of
the easiest functions to learn and use. The plot command is basic, yet most widely used

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 56 1/15/2014 12:48:38 PM


57 Ñ 2-Dimensional Plots

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

Time for Practice 3.1


Complex number identity e jq = cos q + j sin q, is often used for simplified operations in many
engineering equations. Confirm this identity by plotting the imaginary part versus real part
of both the left- and right-hand sides over the interval -p ≤ q ≤ p.

Figure 3.1 shows the resultant plot.


In general, you can use plot(X,Y)only when X and Y are vectors of same length. They can
be either row or column vectors. The swapping of arguments X and Y simply interchanges the
axes, as if the same plot has been rotated. Type the following and note the outcome:
>> plot (Y,X)
40

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

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 57 1/15/2014 12:48:39 PM


MATLAB Graphics and Plotting  É 58

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:’)

Time for Practice 3.2


The hyperbolic sine function is defined by the equation:
sinh(x) = (ex - e-x)/2
Plot the values of the function for -3 ≤ x ≤ 3 and compare your plot with the plot of MATLAB
intrinsic function sinh(x) for the same range of x.

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

Figure 3.2  X-Y plot with line style and color

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

Colors Marker Styles Line Styles


b blue . point v triangle (down) - solid
g green o circle ^ triangle (up) : dotted
(Continued)

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 58 1/15/2014 12:48:39 PM


59 Ñ 
  2-Dimensional Plots

Table 3.1  (Continued)

r red x x-mark < triangle (left) -- dashed


c cyan + plus > triangle (right) -. dashdot
m magenta * star p pentagram
y yellow s square h hexagram
k black d diamond

Table 3.2  Important commands associated with plotting

clf : Clears the current plot and leaves it blank


figure : Opens a new figure to plot on
close : Closes the current figure window
loglog : Same as plot, except both axes are in log (base 10) scale
semilogx : Same as plot, except x-axis is log (base 10) scale
semilogy : Same as plot, except y-axis is log (base 10) scale
plotyy : Plots two different functions on common x axis and two
different y-axes on both sides
grid : Adds grid lines to your plot
ginput : Provides a means of selecting points from the current plot
using the mouse. [x, y] = ginput(n) gets up to n points from
the current axes and returns their coordinates in the column
vectors x and y. If n is omitted, an unlimited number of points
are gathered until the Return or Enter key is pressed.

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)).

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 59 1/15/2014 12:48:39 PM


MATLAB Graphics and Plotting  É 60

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

3.3  Plot Aesthetics


Proper labeling and annotation of a plot is also extremely important to extract any useful information
from the given plot. In the following sections, plot labeling is illustrated through various examples.

3.3.1  Changing the Axes


One of the important features in the clarity of a plot is proper selection of the axes ranges. For
instance, in order to plot the function y = exp (5t) - 1, enter the following command at the
MATLAB prompt:
>> T = 0:0.01:5;
>> Y = exp (5*T)-1;
>> plot (T,Y)
The resultant plot is shown in Figure 3.4.

× 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

Figure 3.4  An exponential plot

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 60 1/15/2014 12:48:40 PM


61 Ñ 
  Plot Aesthetics

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.

3.3.2  Adding Text


Appropriate labeling of the axes is an important part of plotting. A plot can be given a title using
the title command, x-axis label using the xlabel command and y-axis label using the
ylabel command. These commands should be entered after executing the plot command
(i.e., after plotting the figure).
A title should be placed at the center and above the plot figure with the following command:
>> title (‘title string’)

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 61 1/15/2014 12:48:40 PM


MATLAB Graphics and Plotting  É 62

The x-axis is labeled with the following command:


>> xlabel(‘x-axis string’)
Similarly, the y-axis is labeled with the following command:
>> ylabel(‘y-axis string’)
Let us again consider the Figure 3.5 of plotting the function y = exp(5t  - 1). Assuming that the
axis is already changed, the plot can be labeled by executing the following code after executing
the axis command:
title(‘an exponential plot’)
xlabel(‘time (sec)’)
ylabel(‘the function values, specified units’)

The plot appears as shown in Figure 3.6.


Furthermore, any other text can be inserted at any location inside the plot in one of the fol-
lowing two ways:
1. Using the text command: This involves knowing the exact coordinates of the point where
you wish to insert the text string. The syntax is as follows:
text(x_coordinate,y_coordinate,‘textstring’)
Using the gtext command: The syntax of this command is as follows:
2. gtext(‘textstring’)
After executing this command, a cross-hair will appear in the plot window. You should move the
cross-hair to the desired location with the mouse, and click at the position where you wish the
text string to be inserted. Thus, you do not need to know the exact coordinates of the location
of the text string.
An exponential plot
50

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)

Figure 3.6  Plot of function y = exp (5t - 1) with appropriate labeling

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 62 1/15/2014 12:48:40 PM


63 Ñ 
  Plot Aesthetics

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)

Figure 3.7  Adding text at any location

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 63 1/15/2014 12:48:40 PM


MATLAB Graphics and Plotting  É 64

3.4  Multiple Plots


Situations arise, whereby one may be required to plot a number of functions in different figures or
multiple functions in the same figure. Consider the case where an electrical engineer is interested to
plot both the current drawn and the power consumed by a device as a function of time in the same
figure. The following piece of code is an initial attempt to create multiple plots in the same figure:
>> X = linspace (0,2*pi,50);
>> Y = sin(X); % Y is the first function of X
>> Z = cos(X); % Z is the second function of X
>> W = tan(X); % W is the third function of X

Let us plot the data Y versus X:


>> plot (X,Y)
Figure 3.8 shows the result of executing this command.
Now let us plot data Z versus X using the following command:
>> plot (X,Z)
The resulting plot is shown in Figure 3.9.
The cosine plot is displayed in the same figure window as the sine curve, but the sine curve is
superseded by cosine curve. In other words, the sine curve is no longer displayed. However, for
the sake of comparison or other similar reasons, you may wish to see both the sine and cosine
plots simultaneously. For displaying each plot in a separate figure window, the following com-
mand is used:
>> plot (X,Y)
>> figure
% this command will create a new figure window to
% be used for your next plot
>> plot (X,Z)

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.8  A sine curve

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 64 1/15/2014 12:48:41 PM


65 Ñ 
  Multiple Plots

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

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 65 1/15/2014 12:48:41 PM


MATLAB Graphics and Plotting  É 66

3.4.1  Multiple Plots on a Window


Following are the two ways to plot multiple functions in a single window:
1. Using a single plot command: The first one is to use only one plot command with the
parameters for all functions to be plotted.
2. Using multiple plot commands: The second one is to use multiple plot commands but
use the hold on command to plot all curves in a single window.
This example illustrates the usage of a single plot command. The following M-file can be
used to plot a sine wave and a cosine wave on the same set of axes, using different colors and
point markers:
mult_plot1.m
X = linspace(0,2*pi,50);
% Take 50 samples for x in range 0 to 2*pi

Y = sin(x);
Z = cos(x);
plot (X,Y,‘r’,X,Z,‘bx’)
% could be more than two plots as well

legend (‘sinx’, ‘cosx’, 0)


% This is for labeling the two curves

Time for Practice 3.3


Find graphically an approximate value of the root of the equation: 3 -  x = e x-1
(Hint: Plot the two curves y = 3-x and y = e x-1 on the same window)

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.

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 66 1/15/2014 12:48:41 PM


67 Ñ 
  Multiple Plots

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

Figure 3.10  Multiple plot example

Time for Practice 3.4


Find graphically the lowest root of the equation in the interval [0, 2*pi].
cos(x)cosh(x)= -1
(Hint: Plot the two equations y = cos x and y = -sech (x) on the same plot and find their
intersection.)

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

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 67 1/15/2014 12:48:41 PM


MATLAB Graphics and Plotting  É 68

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.

3.4.2 Some Important Functions on Multiple Plots


The general form of the plot command used for multiple plots is:
plot (x1,y1, ‘style1’, x2,y2,‘style2’,...,xn,yn, ‘style-n’)

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

Year 1997 1998 1999 2000 2001 2002 2003


Yearly Rainfall (in cm) 64.5 72.1 68.7 67.9 68.3 62.5 67.5
Rice Pdn (in million tonnes) 4.47 4.52 4.95 5.12 5.10 4.37 5.13

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];

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 68 1/15/2014 12:48:41 PM


69 Ñ 
 Subplotting

crop = [4.47 4.52 4.95 5.12 5.10 4.37 5.13];


% above three variables take the respective data
% in vector forms.
plot (years,rain,‘r’, years,crop,‘bx-.’)
% plots the given yearly data for rain and crop
% yield on the same figure window

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

Figure 3.11  Multiple plots for data with distinct ranges

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 69 1/15/2014 12:48:42 PM


MATLAB Graphics and Plotting  É 70

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

Figure 3.12  Multiple functions plotting by using subplot  command

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 70 1/15/2014 12:48:42 PM


71 Ñ 
 Subplotting

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

Figure 3.13  Subplots with one position empty

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 71 1/15/2014 12:48:42 PM


MATLAB Graphics and Plotting  É 72

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

Average rainfall (cm)


Crop yield (million tonnes)
70 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.

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 72 1/15/2014 12:48:43 PM


73 Ñ 
  Some Other Useful 2-D Plots

3.6  Some Other Useful 2-D Plots


The plot command generates a linear plot. Although, linear plots are most widely and
frequently used, other important plot types such as pie charts, bar charts, and logarithmic plots
are also useful. MATLAB provides an easy way to create many such plot types. Following are
a few examples on some of the important plot types:

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.

House-hold Monthly Budget Table

Budget Component Total Expenditure (in `)


Essentials 5,000
Luxuries 8,000
Entertainment 2,000
Children’s education 5,000
Medical care 1,500
Savings 2,500
Grand total (`) 24,000

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

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 73 1/15/2014 12:48:43 PM


MATLAB Graphics and Plotting  É 74

A Typical Household’s monthly budget


Savings
Essentials
Medical care

Children’s education

Luxuries
Entertainment

Figure 3.15  Using pie command for plotting data

The resultant plot is as shown in Figure 3.15.

Time for Practice 3.5


Example 3.6 depicts various components of the budget according to their percentage share
in total expenses. Please show the corresponding % share in numbers in the pie chart and
also label each component.

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’)

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 74 1/15/2014 12:48:43 PM


75 Ñ 
  Some Other Useful 2-D Plots

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.

Time for Practice 3.6


Execute the command
>> bar (x, n),
for x and n vectors obtained in the previous example and compare the resultant plot with this.

Marks distribution in subject abc


14

12

10
No. of students

0
0 5 10 15 20 25 30 35 40 45 50
Marks ranges

Figure 3.16  Drawing a histogram

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 75 1/15/2014 12:48:43 PM


MATLAB Graphics and Plotting  É 76

Time for Practice 3.7


Draw a histogram and frequency polygon for the following distribution. Also calculate the
average marks of the students of this class.

Marks Below No. of Students Marks Below No. of Students


10 15 50   96
20 35 60 127
30 60 70 198
40 84 80 250

(Hint: arithmetic mean of a grouped data = S x.*n/S n)

3.7  Advanced Concepts on Plot Annotation and Labeling


Sometimes you have to use specific font types, font sizes, and font faces (bold/italic). In scien-
tific presentations you may need to use certain notations and symbols while labeling your plots.
Consider the previous example of the exponential function in section 3.3.

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

3.7.1  Using Handle Graphics


Whenever a plot is created, MATLAB defines a handle to all the important objects (such as
axes, labels, curve, and the figure itself) in the plot. A handle can be thought of as an identity
or an address of a particular object within a plot. MATLAB assigns an address to each object.
If you provide that address, MATLAB can also retrieve a list of the current properties of that
object. You can then change any desired property and feature of the object.
For example, executing subplot (2,2,1) will give the handle of the current object. In
this case, the handle is the first partition in 2 × 2 partition matrix. Hence, future plot edit-
ing commands will be applicable to this current handle. Suppose you now want to get hold
of the third plot in the sequence of four subplots. You may write ­ subplot(2,2,3),
and then you can manipulate the third plot. The idea behind the handle of any object
in the plot is the same. Once the handle of an object is selected, subsequent commands

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 76 1/15/2014 12:48:43 PM


77 Ñ 
  Advanced Concepts on Plot Annotation and Labeling

manipulate this object. Following are some of the important MATLAB functions on
handles:

gca: get handle to current axes


gcf: get handle to current figure
gco: get handle to current object

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

On executing the get(h1)command, MATLAB responds with several properties, some of


which are shown here:
FontAngle = normal
FontName = Helvetica
FontSize = [10]
LineWidth = [0.5]

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,.............)

This example illustrates the usage of set command:

>> figure
>> h1 = gca;

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 77 1/15/2014 12:48:43 PM


MATLAB Graphics and Plotting  É 78

>> set(h1, ‘FontSize’,12,‘FontWeight’,‘bold’)


>> plot (2:8, 3:9)
% this plot will be with the axes properties in
% previous command
>> set(h1, ‘FontSize’,20,‘FontWeight’,‘bold’)
% changes the axes properties as per the
% specifications given

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’)

Example 3.8 Example 3.8:


Consider the plot of the function y = exp(5t) -1. Use set command Setting the
to assign the plot parameters. parameters of
axes and labels in
Solution a plot
Enter the following commands at MATLAB prompt and observe
the changes in plot, every time you enter the next command:

>> 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.

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 78 1/15/2014 12:48:43 PM


79 Ñ 
  Advanced Concepts on Plot Annotation and Labeling

The final plot is shown in the Figure 3.17.


Plot for y = e5t − 1
50
45
40
35
y, Specified units

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

Figure 3.17  Plot annotation with handle graphics (Example 3.8)


Note: It is recommended to give the variable name for a certain object property exactly the
same way as you find them with the get(handle-name) command. Defining any arbitrary name
might cause an error. For example, if you write set(gca, ‘XLimit’, [0 1] ) in the
program, it will cause an error as the pre-defined variable for X-axis limits is XLim.

Time for Practice 3.8


Plot the function y = e5t -1 with the following plot annotation:

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

Figure 3.18  A parallel RC circuit

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 79 1/15/2014 12:48:44 PM


MATLAB Graphics and Plotting  É 80

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’)...

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 80 1/15/2014 12:48:44 PM


81 Ñ 
  Advanced Concepts on Plot Annotation and Labeling

% this uses LaTeX interpreter. Note the use of


% \leftarrow for a % left arrow symbol and
% upward arrow followed by braces, for upper
% case letters.
text (1.9,0.1, ‘RC’, ‘fontsize’, 10)
% inserts a text at a selected coordinate,
text (3.8,0.1, ‘2RC’, ‘fontsize’, 10)
% first two arguments are x and y coordinates
% respectively
text (5.8,0.1, ‘3RC’, ‘fontsize’, 10)
text (7.8,0.1, ‘4RC’, ‘fontsize’, 10)
box off
% will remove the box/frame around the figure.
h3 = line ([0 R*C], [v_init 0]); % h3 is handle to
% a line, whose two end coordinates are given as arguments to
the ‘line’ command
set(h3, ‘linestyle’, ‘:’)
% changes the properties of the above line
% through its handle h3
gtext(‘tangent to curve’, ‘fontsize’, 9, ‘Rotation’, 282)
% this command lets you place a text at any
% location in the plot. After the figure is
% drawn, it waits for input from the user.
% Pressing the mouse button at a particular
% location in the graph writes the text string
% at that location

The code is saved in the file “Parallel_RC.m”. Executing the file generates the plot as
shown in Figure 3.19.

Natural response of a first order RC circuit


5

4
V(t), volts

3
V(t) = v(0). E−t/rc
Tang

2
e
t to c

1
urve

Rc 2rc 3rc 4rc


0
0 2 4 6 8 10
T, sec

Figure 3.19  A plot annotation with handle graphics (Example 3.9)

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 81 1/15/2014 12:48:44 PM


MATLAB Graphics and Plotting  É 82

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

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 82 1/15/2014 12:48:44 PM


83 Ñ 
  Advanced Concepts on Plot Annotation and Labeling

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’)...

Figure 3.20 shows the resultant plot.


Be specific in writing codes for the LaTeX interpreter. For example, consider the second last
line of the code in example 3.10:
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.

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 83 1/15/2014 12:48:44 PM


MATLAB Graphics and Plotting  É 84

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

Figure 3.20  Plot annotation with handle graphics

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

a : alpha r : rho G: Gamma ∫ : int ì : propto


b : beta s : sigma D: Delta S: sum °: circ
g : gamma t : tau L: Lamda @: cong É : infty
d : delta w : omega P: Pi ~: sim ′: prime
e : epsilon k : kappa S: Sigma ≠: neq ←: leftarrow
h : eta x : xi W: Omega ≥: geq ⇐: Leftarrow
q : theta o o Q: Theta ≤: leq →: rightarrow
l : lambda u : upsilon X: Xi >>\gg ↑: uparrow
m : mu z : zeta ϒ: Upsilon <<\ll ↓: downarrow
n : nu c : chi F: Phi ±: pm ∠: angle
p : pi y : psi Y : Psi ×: times √: surd
f : phi i: iota ÷: div $: $

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 84 1/15/2014 12:48:45 PM


85 Ñ 
  Advanced Concepts on Plot Annotation and Labeling

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.

3.7.2  An Easier Way to Plot Editing


Proper annotation of a plot may be more difficult than plotting itself. You may have to deal with
not just labeling of axes, giving a title, adding texts, and suitable legends at appropriate places,
but also selecting suitable axis limits, line types, markers, and colors. In addition, suitable
choice of font types and sizes and adding special characters and symbols are also to be consid-
ered. Using handle graphic notations for each case may turn out to be a tedious task.
There is an easier method to edit the plots in a dynamic way using the Graphical User
Interface (GUI) available in the figure window. Take the example of one of the plots that was
created previously. The code is reproduced as follows:
x = linspace(0,2*pi,50);
y = sin(x);
z = cos(x);
plot (x,y,‘r’, x,z,‘bx’)
legend (‘sinx’, ‘cosx’, 0)

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.”

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 85 1/15/2014 12:48:45 PM


MATLAB Graphics and Plotting  É 86

Figure 3.21  Plot displaying the “figure toolbar”

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. Opens a new figure window.


2. Opens an existing figure file.
3. Saves the current figure to a file.
4. Prints the plot.
5. Invokes the plot editing tool to access and modify various plot characteristics and
labeling.
6. Zooms in (or magnifies) a selected portion of the plot (use mouse drag to select the portion
after you invoke this tool).

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 86 1/15/2014 12:48:45 PM


87 Ñ 
  Advanced Concepts on Plot Annotation and Labeling

Edit plot mode

Figure 3.22  Plot annotation through “figure toolbar”

1 2 3 4 5 6 7 8 9 10 11 12

Figure 3.23  Shortcuts on a figure toolbar

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.

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 87 1/15/2014 12:48:45 PM


MATLAB Graphics and Plotting  É 88

11. Inserts a colorbar.


12. Adds a legend to selected axes on a graph for describing the graphs.

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.

Figure 3.24  Using the curve fit

Time for Practice 3.9


The rainfall data for New Delhi for all the months in a certain year are given as follows:
Month Rain (mm)
Jan 22.7
Feb 20.1
Mar 14.5

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 88 1/15/2014 12:48:46 PM


89 Ñ 
  3-D Graphics

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.

3.8  3-D Graphics


3-D plots play an important role in plotting functions that cannot be interpreted properly in the
2-D plane. For instance, to know the nature of a function z which depends on two variables x
and y, you need a 3-D plot. MATLAB has several built-in functions for plotting 3-D objects.
This subsection deals mostly with functions used to plot curves in the 3-D space (plot3),
mesh surfaces (mesh), plain surfaces (surf), and contour plots (contour). Also, two
functions for plotting special surfaces namely, sphere and cylinder are discussed briefly.
You can use MATLAB help on 3-D plots (>> help graph3d), to find more information
on certain plot features. Here is an illustration of a 3-D plot.
An object moving over the x-y plane is governed by the following equations in time t:

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);

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 89 1/15/2014 12:48:46 PM


MATLAB Graphics and Plotting  É 90

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];

Curve u(t ) = < t *cos(t ), t *sin(t ), t >

40

20
Time

− 20

− 40
40
20 40
0 20
0
−20 −20
y − 40 − 40
x

Figure 3.25  A simple 3-D plot

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 90 1/15/2014 12:48:46 PM


91 Ñ 
  3-D Graphics

Time for Practice 3.10


Conduct the following plot editing over the previous plot (a) with the help of handle graphics
commands, (b) with Figure Toolbar:
1. Set the x-label, y-label, and z-label in bold face letters of size 10.
2. Change the line width of the curve to 1.5 points and line color as magenta.
3. Change the title font to Courier New, Font Size to 14 in Italics.

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

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 91 1/15/2014 12:48:46 PM


MATLAB Graphics and Plotting  É 92

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

This code results in the plot depicted in Figure 3.27.


The function surf is used to visualize the data as a shaded surface.
The m-file “graph5” shows the code that illustrates some other 3-D plots and aspects of
3-D graphics in MATLAB.

Figure 3.26  A mesh plot of a hyperbolic paraboloid

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 92 1/15/2014 12:48:48 PM


93 Ñ 
  3-D Graphics

Figure 3.27  Mesh and contour plot of a hyperbolic paraboloid

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

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 93 1/15/2014 12:48:50 PM


MATLAB Graphics and Plotting  É 94

% opens a new figure window for the next plotcontourf(zi),% gener-


ates a filled contour plot
hold on,
% hold on the current figure window shading flat
% controls the color shading used to paint the
% surface
[c,h] = contour(zi,‘k-’)
% This is a contour plot over the previous
% figure;
% c is the contour matrix and
% h is handle to line objects
clabel(c,h)
% label the contours according to their
% elevation levels
title(‘The level curves of z = y^2 - x^2.’)
xlabel(‘x’)
ylabel(‘y’)

>> 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

Figure 3.28  Surface and contour plot of the hyperbolic paraboloid

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 94 1/15/2014 12:48:50 PM


95 Ñ 
  3-D Graphics

The level curves of z = y 2 − x 2


0.6
40 0.8 0.8 0.4
0
35 −0 0.4 0.6
.4 .4
0.4
2 2 −0

−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

Figure 3.29  Level curves for the hyperbolic paraboloid

1.5

0.5

0
0
−0.5 3
−1 2.5
2
−1.5 1.5
−2 1

Figure 3.30  Surface plot of a sphere

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 95 1/15/2014 12:48:51 PM


MATLAB Graphics and Plotting  É 96

Time for Practice 3.11


Obtain the surface and contour plots for the function z = x2 – 2xy + 4y2 showing the minimum
at x = y = 0.

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

Time for Practice 3.12


Obtain the surface and contour plots for the function z = (x - y 2) (x - 3y 2). This surface has a
singular point at x = y = 0, where the slope of the surface is zero, but this point does not corre-
spond to either a minimal or a maximal. What is the nature of contour lines at a singular point?

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

tion sphere is called without any input parameter, MATLAB


uses the default value n = 20. You can also translate the center of the sphere. The
following example illustrates plotting the graph of a unit sphere with center at
(2, -1, 1):
>> [x,y,z] = sphere(30);
>> surf(x  +  2, y  -  1, z  +  1)
The function sphere can be used together with the function surf or mesh to plot graphs of
spheres of arbitrary radii. Also, they can be used to plot graphs of ellipsoids.
The function cylinder is used for plotting a surface of revolution. It takes two (optional)
input parameters. In the following command cylinder(r, n),  the parameter r is a vector
that defines the radius of the cylinder along the z-axis, and the parameter n specifies the number
of points used to define the circumference of the cylinder. Default values of these parameters
are: r = [1 1] and n = 20. The generated cylinder has unit height.
The following commands plot a cone with unit radius and unit height. The plot appears in
Figure 3.31.
>> cylinder([1 0])
>> title(‘Unit cone’)

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 96 1/15/2014 12:48:52 PM


97 Ñ 
  3-D Graphics

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

Figure 3.31  Plotting a unit cone

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

Figure 3.32  Plot of a curve

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 97 1/15/2014 12:48:52 PM


MATLAB Graphics and Plotting  É 98

0.8

0.6

0.4

0.2

0
1
0.5 1
0 0.5
0
−0.5
−0.5
−1 −1

Figure 3.33  Plotting the surface of revolution for the curve

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

3.9  Function Plotters


In order to plot a function, you must know the ranges of the variables in the function. The func-
tion can then be evaluated at each point within the range. Finally, you can plot the function for
the given variable ranges. You can also do this directly. You just define the function; specify the
variable ranges, and the plot will be generated by the plotter for the given variable range.

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 98 1/15/2014 12:48:53 PM


99 Ñ 
  Function Plotters

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

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 99 1/15/2014 12:48:53 PM


MATLAB Graphics and Plotting  É 100

x 2 + y 2 − 4xy + 1/5 = 0
3

0
y

−1

−2

−3
−3 −2 −1 0 1 2 3
x

Figure 3.34  Plot using a function plotter

% domain: -2*pi < x < 2*pi.ezplot(f,[min,max])


% plots f = f(x) over the domain: min < x < max.

For implicitly defined functions, f = f(x,y):


ezplot(f) % plots f(x,y) = 0 over the default domain
% -2*pi < x < 2*pi, -2*pi < y < 2*pi. ezplot(f,[xmin,xmax,ymin,ymax])
% plots f(x,y) = 0 over xmin < x < xmax and ymin < y < ymax.
ezplot(f,[min,max]) % plots f(x,y) = 0 over
% min < x < max and min < y < max.

Time for Practice 3.13


To compute the forces in structures, you come across the equations similar to the following.
Use the fplot function to find all the positive roots of the equation: x tan (x) = 7.

Time for Practice 3.14


Plot the following expressions as x-y plots using MATLAB function plotters:
1. 1/y - log(y) + log(-1 + y) + x - 1 = 0
2. x = sin(3*t)*cos(t), y = sin(3*t)*sin(t); 0 < t < pi

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 100 1/15/2014 12:48:53 PM


101 Ñ Programming Tips and Pitfalls

Time for Practice 3.15


Enter the following commands at your MATLAB prompt and comment on the resultant plots:
1. ezpolar(‘sin(2*t)*cos(3*t)’,[0,pi ])
2. r = ‘100/(100 + (t-1/2*pi )^8)*(2-sin(7*t) -1/2*cos(30*t ))’; ezpolar
(r,[ -pi/2,3*pi/2]);

Programming Tips and Pitfalls


Following are the programming tips and pitfalls:
1. Sometimes errors such as segmentation violations, bus errors, floating point exceptions, and
illegal instructions occur when printing. Usually these error messages result from an incom-
patibility between MATLAB and the printer driver. They occur when MATLAB detects a
memory fault because of an unexpected modification that the printer driver makes to the
Floating-point Unit (FPU) of the computer. Alternatively, you can use other printer drivers
that are compatible with your printer. You can also obtain the printer drivers from the printer
manufacturer.
2. Check the following before plotting:
(a) Which is the active figure that you are plotting upon?
(b) Is “Hold on” or “Hold off” used?
(c) Are the rows and columns correct or are they interchanged?
3. Always remember that plotting is an expensive process and should be used only when
needed. If you place a plot command inside a loop, you will find that your program runs
significantly slower.
4. Remember to use proper viewpoints for plotting 3-D data. You can use viewpoint selec-
tion after creating the plot and manually fix the viewpoint at which you obtain the best
resolution.

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.

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 101 1/15/2014 12:48:54 PM


MATLAB Graphics and Plotting  É 102

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.

Year 1996 1997 1998 1999 2000


Temperature (çC) 32 32.5 33 33 34

  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.

Year 1974 1977 1980 1986 1986 1989 1992 1995


Tonnes 100 200 500 1300 6400 12200 20200 26100

(Hint: use “Data Statistics” option in Tools menu on your figure toolbar)

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 102 1/15/2014 12:48:54 PM


103 Ñ 
 Exercises

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.

T (degrees K) 273 278 283 288 293 298


P (torr) 4.579 6.543 9.209 12.788 17.535 23.7563

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

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 103 1/15/2014 12:48:55 PM


MATLAB Graphics and Plotting  É 104

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:

3.13. The parametric equations of a cone is as follows:


h−u h−u
x=r cosq ; y = r sinq ; z = u
h h
Where, r is the base radius, h is the height from the base and u ∈[0, h] and u ∈[0, 2p ].
Use plot3 command to plot a cone with r = 2 units and h = 4 units.
3.14. Use the surf and mesh commands to plot the above cone using the same x, y and z
coordinates.
3.15. In the spherical coordinate system, the coordinates for a sphere are given as: q, the azi-
muthal coordinate varies from 0 to 2p (longitude), Φ, the elevation angle varies from
0 to p (co-latitude), and r is the radius. Given that r = 3 units, convert the data points into
Cartesian coordinates and then plot the sphere using surf command. Set “Flat” shading
to the plot and use color bar to indicate the heights of different points over the surface.
3.16. Obtain the surface and contour plots for the function z = –x2 + 2xy +3y2. This surface has
a saddle point at x = y = 0, where the slope of the surface is zero, but this does not corre-
spond to either a minima or a maxima. What types of contour lines correspond to a saddle
point?
3.17. A square metal plate is heated to 80°C at the corner corresponding 2
to2 x = y = 1. The tem-
perature distribution in the plate is described as: T = 80e − ( x −1) e −3( y −1) . Obtain the surface
and contour plots for the temperature. Label the axes and the plot appropriately. What is
the temperature at the corner corresponding to x = y = 0?

M03_PROGRAMMING IN MATLAB_XXXX_CH03.indd 104 1/15/2014 12:48:56 PM

You might also like