Anda di halaman 1dari 39

Introduction to Computing with

MATLAB

Addis Ababa University


School of Graduate Program and Research

August 31-September 6, 2011

Outline of Lecture four


Graphics
Two Dimensional Plotting
Specialized 2D Plot Functions
Three Dimensional Plotting
Surface Plotting

MATLAB

Importing

MATLAB Graphics into MS Applications

7. MATLAB Graphics
The MATLAB environment supports graphic display of a known
function, data resulting from experimental measurements or from
engineering and/or scientific computation through various built-in
functions for plotting.
It also provides control facility over graphic properties.

7.1 Two Dimensional Plotting


The most commonly used graphics display function in MATLAB is the function
plot, and the syntax is plot(x,y), where x and y are two n-dimensional arrays.
Example

X = [1 2 3 4 5 6] and Y = [1 4 9 16 25 36]

The following lines of commands plots the array Y against array X

>> X = [1 2 3 4 5 6];
>> Y = [1 4 9 16 25 36];
>> plot(X,Y)
Six data points are given to MATLAB and then the function plot connected these
consecutive points with lines, i.e. interpolates the data points
If an analytic formula of a function

is known then to visualize its graph


we dont need to list the discrete
points, it suffice to discretize the
domain, MATLAB can then evaluate
the function at each discrete point in
the domain and render the data points
for interpolation.
We can discretize a domain either

by using the colon : operator or


using MATLAB built-in functions

Example
Consider the interval, I = [1, 6] of the real line.
>> X=1:6
X=
123456
The colon operator : as used above, generates the discrete representatives of the
given interval with the difference between any two consecutive members 1, called
the step size. This is the default use of the colon operator.
In the general case, one specifies the step size r, a number larger or may be
smaller than 1 depending on the number discrete points he need for his purpose.
>> z = 1:0.5:6
z=
Columns 1 through 7
1.0000 1.5000 2.0000 2.5000 3.0000
3.5000 4.0000
Columns 8 through 11
4.5000 5.0000 5.5000 6.0000

This are discrete representatives of the same


interval I = [1,6], generated with step size 0.5.
Among several MATLAB built-in functions,
linspace that can do the same job

>> x = linspace(1,6,11)
x=
Columns 1 through 7
1.0000 1.5000 2.0000 2.5000
3.0000 3.5000 4.0000
Columns 8 through 11
4.5000 5.0000 5.5000 6.0000
In the argument of the MATLAB function linspace, 11 represents
the number n of discrete points needed, while 1 and 6 are the left and
right end points of the interval. The default value of n is 100.
>> x=linspace(-4,5);
>> y=x.^3-2*x.^2-x+2;
>> plot(x,y)
>> grid
>> title('The Graph of y = x^3-2x^2-x+2')

The function grid forces MATLAB to turn on the current axes' grid lines while
the function title outputs the preferred string at the top and in the center of the
current axes. The Syntax is, title('string').

Multiple graphics
We can visualize the plot of two or more graphs on the same set of axes.
These can be done either by plotting them both at the same time, the syntax is
plot(x, f, x, g) or through the use of the command hold on/off. In what
follows, we try to visualize the graphs of

in one and the same set of axes, by plotting them at the same time.

>> x=linspace(-4,5);
>> f = x.^3 - 2.*x.^2 - x + 2;
>> g= 2.*x.^3+2;
>> plot(x,f,x,g,'.-')
>> legend('y = x^3-2x^2-x+2','y=2x^3+2')
>> grid

Next we shall use the command hold on/off to generate the same set of
graphics with MATLAB as the preceding one. In this case, we call the function
plot twice between the commands hold on and hold off as indicated bellow.

>>x=linspace(-4,5);
>>f = x.^3 - 2.*x.^2 - x
+ 2;
>>g = 2.*x.^3+2;
>>hold on
>>plot(x,f)

>>plot(x,g,'.-g')
>>hold off
>>legend('y = x^3-2x^2-x+2','y=2x^3+2')
>>grid

One can use a single window to visualize several plots one after the other without
overlay. The command clf ensures an empty figure window. In case a graphics window
is hidden under other active windows on the desktop, the command shg helps bring
graphics window to the front.

Plotting Options
When visualizing several plots on the same set of axes one has to do something
to distinguish between different plots. MATLAB has a facility that enable us do
this.
Each plot can be given its own distinctive look by modifying, either the way the
points are plotted i.e. as a solid line, as points, as point-line etc, or by using
different colors green blue, red, etc for different curves.
These graphic features are specified by introducing a 3rd argument in the function
plot, The syntax is plot(x,y,s) where s is a character string composed of a letter
for color and others for line type and plot symbol.

Possible colors we may use are as depicted


in the following table. The default color is
blue.

When plotting a line, we


may change the appearance
of a line by using one of the
following characters

The default line is solid.


In plotting curves it is
possible to use symbols
rather than lines, we can do
this by using any one of the
following symbols

We might want to visualize several plots side by side, without overlaying


them. In MATLAB this is possible.
To display multiple plots in the same window but with different axes, the
built-in function subplot divides the current figure window into rectangular
panes with each pane containing an axes object such that subsequent plots are
displayed on the current pane.
The syntax is subplot(m,n,p) or just subplot(mnp). The command
subplot(mnp), partitions the figure window into an m-by-n matrix of small
axes and then selects the p^th axes for the current plot. The axes are counted
from left to right along rows of the figure window starting with the first.
>>x=linspace(-6,8);
>>f = x.^3 - 2.*x.^2 - x + 2;
>>g= -2.*x.^3+2;
>>h=sin(x);
>>k=cos(x);
>>subplot(221)
>>plot(x,f)
>>legend('y = x^3-2x^2-x+2')

>>grid
>>subplot(222)
>>plot(x,g,'g')
>>legend('y=-2x^3+2')
>>grid
>>subplot(223)
>>plot(x,h,'c')
>>grid

>>legend('y=sinx')
>>axis([-6 8 -2 2])
>>subplot(224)
>>plot(x,k,'m')
>>axis([-6 8 -2 2])
>>legend('y=cosx')
>>grid

The above figure window is subdivided into 2 x 2 matrix of separate axes and is
generated with the script in previous slid

7.2 Specialized 2D Plot Functions


A) Implicit Plot
Thus far, we have been displaying the graph of a function f which has
explicit analytical formula/expression.
The MATLAB built-in function plot, accepts the discritized domain (an
array X), evaluates f at each xX (generates an array Y) and then
returns graphics which is the plot of vector Y against vector X.
If a function f of two variables is defined implicitly, such a procedure
may not apply and hence the built-in function plot can not be used.
In such a situation, the other MATLAB built-in function plotter ezplot
serves the purpose. The syntax is
ezplot(f, [a,b,c,d])

where a x b and c y d.

The default configuration of this plotter function is ezplot(f) and the


corresponding default domain is -2 x 2 and -2 y 2 .
In the event that a = c and b = d, it suffices to write ezplot(f, [a,b])

For implicitly defined function f(x,y) ezplot(f, [a,b,c,d]) plots f(x,y) = 0 over
the domainD = {(x, y) : a x b,c y d}.
Example
>> ezplot('cos(x^2 - y^2)',[-3,3,-4,4])

B) Parametric Plot

Example
>> ezplot('sin(t)','cos(t)')
>> grid
The graph of a function, y =
f(x) of a single-variable x
can be displayed in
MATLAB using the function
ezplot , the corresponding
syntax is ezplot(f,[a,b]).

Example
>> ezplot('sinh(x)',[-3,3])
>> grid

C) Field Plot
In MATLAB, we can display a vector quantity, r = u i + vj e.g. velocity
of a wind, the velocity of flow of a fluid etc, measured at uniformly
spaced points in a two dimensional domain D.
The plotter function used to display a vector field would exhibit an
arrow at each data point (x,y), whose direction and magnitude
corresponded to the value (u(x,y),v(x,y)). For two dimensional case,
such a plot can be achieved with the built-in function quiver.

Example
Suppose f(x, y) = -yi + xj defined over the
rectangle [2, 2] [-2,2]. To display the plot
of the vector field, we write the following

>> u=inline(-y,x,y)
>> v=inline(x,x,y)
>> x=linspace(-2,2,11);
>> y=linspace(-2,2,11);
>> [X,Y]=meshgrid(x,y);

>> U=u(X,Y); V=v(X,Y);


>> quiver (X,Y,U,V)
>> axis image
>> title(f(x,y)=-yi+xj)

If you do not care for the crowded appearance of the vectors, you can
display/try the following lines of commands command,
[x,y]=meshgrid(2:0.2:2);
U = -y;
V=x;
quiver(x,y,u,v)
title('r = -y i + x j')
to get the following
graphics with dense,
i.e. larger number of
arrows

D) Contour Plot
In MATLAB, we can plot contour curves of a function, Z = f(x,y) of two
variables.
A contour plot is the level curves of Z corresponding to a given value.
The first step is specifying the domain, i.e. range of values for x & y
and generating grid of points, which can be done by using the meshgrid
command on the given domain.
We then, compute the function value at each point and finally use
MATLAB's contour command to draw the level curves.
The following lines of commands should produce the level curves of

On the domain D = {(x, y) : 0 x 2, 2 y 2}

>> [x,y] = meshgrid(0:.05:2, -2:.05:2);


>> z = x .* exp(-x.^2 - y.^2);
>> contour(x,y,z)

It is possible to label each contour (level curve) with its corresponding


value, a constant value of the function. This can be achieved by rewriting
the previous code (lines of commands) as follows
>> [x,y] = meshgrid(0:.05:2, -2:.05:2);
>> z = x .* exp(-x.^2 - y.^2);
>> [t,h]=contour(x,y,z);
>> clabel(t,h)

If you want to display exactly a given number of contours, you can specify
the number, i.e. how many you want. All you need to do is, introduce a
fourth argument to the function contour
>> [x,y] = meshgrid(0:.05:2, -2:.05:2);
>> z = x .* exp(-x.^2 - y.^2);
>> contour(x,y,z,3)

2d Implicit Plotting Revisited


The MATLAB built-in function contour can also be used to display/plot the
graph of a function defined implicitly. This can be demonstrated by the
following example. Consider the equation

Often, an equation such as this one is difficult (or impossible) to solve for
y in terms of x.
However, one can use MATLAB function contour as an implicit function
plotter, thereby ignoring the need to solve the equation explicitly for y in
terms of x before plotting.
We start by collecting all terms to one side of the equation so as to make
the above equal to zero.

Now, we set

The desired equation then reads

Evidently, the graph of the implicit function is the level curve of f(x; y) = ,
where =0 i.e. a single level curve that can be displayed using the
MATLAB function contour. To render comparison, we shall do this for the
implicit function, cos(x2 y2) = 0 .
<< [x,y] = meshgrid(-3:.05:3, -4:.05:4);
<< z = cos(x.^2 - y.^2);
<< contour(x,y,z,[0,0])

7.3 Three Dimensional Plotting


MATLAB supports display of graphics in three-dimensional space. Lines,
points and surfaces can be visualized by use of MATLAB built-in functions.
A) Curves in 3d
One can display lines and points in 3d with a three-dimensional
counterpart of the function plot.
The MATLAB built-in function plot3 plots points and lines in 3d
space.
The syntax is plot(x,y,z), where x,y and z are arrays/vectors that
have the same size/length.
The command plot3(x,y,z), plots a line through the points whose
coordinates in R^3 are given by x, y and z. Observe here that the
curve is given parametrically.

Example
>> t=0:0.01:37;
>> plot3(sin(t),cos(t),t)
>> xlabel('x'),ylabel('y'),zlabel('z')
>> title('Helix')

As with the built-in function for 2D case, plot the function for 3d, plot3
also has options to specify how a line/point should be plotted.
This preference handled by introducing a fourth argument to the function,
for instance we can change the color of the above helix to one of our
choice, say magenta as follows
>> plot3(sin(t),cos(t),t,'m' )
Line style can also be specified for the plot3 function while plotting a
parametric curve over a domain D R^3 .

B) Parametric curves in 3d

A parametrically defined space curve can also be visualized using the


built-in function ezplot3, a 3d analogue of the parametric curve plotter
function ezplot.
Given any point (x,y,z) on the spatial curve, if (t) = (x(t), y(t), z(t)),
t is a parametric reprsentation then ezplot3(x(t), y(t), z(t), [,])
plots (x(t), y(t), z(t)) over the paramtre set t .

The command, ezplot3(x,y,z) plots the space curve over the default
domain 0 < t < 2*pi, provided that t is declared a symbolic variable.
Example
>> syms t
>> ezplot3(t*sin(t),t*cos(t),t,[0,50],animate)

The last argument


animate is used to
produce animated
trace of the given
space curve.

7.4 Surface Plotting


One can create and display a three-dimensional graphics with MATLAB.
The built-in function surf can be used to create the plot of a threedimensional surface provided that a preferred domain and the
corresponding grid points are furnished.
Example
<< [X,Y] = meshgrid(-2:0.2:2, -2:0.2:2);
<< Z = X.*exp(-X.^2 - Y.^2);
<< surf(X,Y,Z)
<< title('z=xe^{-x^2-y^2}')

The MATLAB command


surf(X,Y,Z ) plots the points
on a grid of the appropriate
size generated by the other
built-in function meshgrid.

The command [X Y] = meshgrid( x, y ); assigns X and Y two matrices,


the first with the x values copied down the columns, and the second with
the y values copied across the rows.
In the above lines of commands keep all but replace the function surf
by another function mesh and then see the change
<<[x,y] = meshgrid(-2:0.2:2, -2:0.2:2);
<<z = x.*exp(-x.^2 - y.^2);
<<mesh(x,y,z)
<<title('z=xe^{-x^2-y^2}')

If the MATLAB built-in function surfc is used instead of either surf or


mesh we will have a surface with adds a contour plot over the domain in
the xy-plane as can be seen below

<<[x,y] = meshgrid(2:0.2:2, -2:0.2:2);


<<z = x.*exp(-x.^2 - y.^2);
<<surfc(x,y,z)
<<title('z=xe^{-x^2-y^2}')

Graphics in 3d, oftentimes represent real world data and hence contour
plots usually permit physical interpretations.
Thus, if a 3d surface is taken to be a topographic map of a mountain then
the corresponding contours represent points of equal elevation or height,
isobars or in case the surface represents a temperature distribution the
contours represent isotherms, points of equal temperature.
MATLAB can be used to visualize not only lines of identical value i.e.
contours but also regions of similar value.
The later is done by using the built-in function contourf, that gives
colorings
Example
>> [x,y] = meshgrid(-2:0.2:2, -2:0.2:2);
>> z = x.*exp(-x.^2 - y.^2);
>> subplot(211)
>> surfc(x,y,z)

>> subplot(223)
>> contour(x,y,z)
>> subplot(224)
>> contourf(x,y,z)

7.5 Importing MATLAB Graphics into MS Applications


Once a MATLAB graphics is generated we might want to insert it into a
word document.
The simplest way of transporting a graphics from MATLAB to a word
document is by a copy-and-paste operation, a two step process.
To this end, go to the Figure window, select the Edit menu and then
choose Copy Figure.
This will send the figure into the Windows clipboard as an enhanced
metafile, .emf format.
Then, in the appropriate part of the MS Word document, position the
cursor and choose Paste.
The clipboard contents can then be pasted into the Word document.

Anda mungkin juga menyukai