Lecture 5
Lecture 5
( 5 )
Plotting Function
MATLAB has extensive facilities for displaying vectors and matrices as graphs,
as well as annotating and printing these graphs.
The plot function has different forms, depending on the input arguments. If y is a
vector, plot(y) produces a piecewise linear graph of the elements of y versus the index of the
elements of y. If you specify two vectors as arguments, plot(x,y) produces a graph of
y versus x. For example, these statements use the colon operator to create a vector of x values
ranging from zero to 2*pi, compute the sine of these values, and plot the result.
x = 0:pi/100:2*pi;
y = sin(x);
plot(y)
28
Experiment No. (5) Plotting Function
plot(x,y)
can you see the difference at x-axis
Various line types, plot symbols and colors may be obtained with plot(x,y,s) where s is
a character string made from one element from any or all the following 3 columns:
29
Experiment No. (5) Plotting Function
Example:
x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;
plot(x1,sin(x1),'r:',x2,cos(x2),'r+')
Example:
x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;
plot(x1,sin(x1),'r:')
hold on
plot(x2,cos(x2),'r+')
30
Experiment No. (5) Plotting Function
The subplot command enables you to display multiple plots in the same window or
print them on the same piece of paper. Typing
subplot(m,n,p)
partitions the figure window into an m-by-n matrix of small subplots and selects the pth
subplot for the current plot. The plots are numbered along first the top row of the figure
window, then the second row, and so on. For example, these statements plot data in four
different sub regions of the figure window.
t = 0:pi/10:2*pi;
x=sin(t); y=cos(t); z= 2*y-3*x; v=5-z;
subplot(2,2,1); plot(x)
subplot(2,2,2); plot(y)
subplot(2,2,3); plot(z)
subplot(2,2,4); plot(v)
31
Experiment No. (5) Plotting Function
By default, MATLAB finds the maxima and minima of the data to choose the axis
limits to span this range. The axis command enables you to specify your own limits
axis([xmin xmax ymin ymax])
The xlabel, ylabel, and zlabel commands add x-, y-, and z-axis labels. The title command
adds a title at the top of the figure and the text function inserts text anywhere in the figure.
Example:
t = -pi:pi/100:pi;
y = sin(t);
plot(t,y)
axis([-pi pi -1 1])
32
Experiment No. (5) Plotting Function
xlabel('-\pi to \pi')
ylabel('sin(t)')
title('Graph of the sine function')
text(1,-1/3,'Note the odd symmetry')
0.8
0.6
0.4
0.2
sin(t)
-0.2
Note the odd symmetry
-0.4
-0.6
-0.8
-1
-3 -2 -1 0 1 2 3
-π to π
33
Experiment No. (5) Plotting Function
Exercises
34