Sei sulla pagina 1di 45

A MATLAB PRIMER

by João Lopes, Vitor Lopes


Contents
1 Getting Started 3
1.1 Starting a Session . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Running a MATLAB Demo . . . . . . . . . . . . . . . . . . . 3

2 Matrix/Vector Operations 4
2.1 Creating and Working with Matrices . . . . . . . . . . . . . . 4
2.2 Basic Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.3 Element-Wise Operations . . . . . . . . . . . . . . . . . . . . 9
2.4 Logical Operations . . . . . . . . . . . . . . . . . . . . . . . . 12
2.5 Selective Indexing . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.6 Polynomial Operations . . . . . . . . . . . . . . . . . . . . . . 14
2.7 Libraries and Search Paths . . . . . . . . . . . . . . . . . . . . 15

3 Graphics 15
3.1 Plotting Individual Graphs . . . . . . . . . . . . . . . . . . . . 15
3.2 Plotting Multiple Graphs . . . . . . . . . . . . . . . . . . . . . 17
3.3 Output of Plots and Graphs . . . . . . . . . . . . . . . . . . . 18
3.3.1 Formatting Plots to Copy/Paste Operations . . . . . . 18

4 Saving Your Work 18

5 Interface Controls 19
5.1 Controlling the MATLAB Session . . . . . . . . . . . . . . . . 19
5.2 Working With the Operating System . . . . . . . . . . . . . . 20

6 For More Help about MATLAB 21


6.1 Online Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

7 Matrix building functions. 21

8 For, while, if and relations. 22


8.1 For. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
8.2 While. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
8.3 If. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
8.4 Relations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

9 Scalar functions. 26

1
10 Vector functions. 26

11 Matrix functions. 27

12 Command line editing and recall. 28

13 Submatrices and colon notation. 29

14 M-files. 30
14.1 Script files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
14.2 Function files. . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

15 Text strings, error messages, input. 35

16 Managing M-files. 36

17 Graphics. 36
17.1 Planar plots. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
17.2 Graphics hardcopy . . . . . . . . . . . . . . . . . . . . . . . . 40
17.3 3-D line plots. . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
17.4 3-D mesh and surface plots. . . . . . . . . . . . . . . . . . . . 41
17.5 Handle Graphics. . . . . . . . . . . . . . . . . . . . . . . . . . 44

2
1 Getting Started
MATLAB (MATrix LABoratory) is an interactive program for scientific and
engineering numeric calculation. Applications include:
• matrix manipulation
• finding the roots of polynomials
• digital signal processing
• x-y and polar plotting
• 3-dimensional graphics
This document assumes a fundamental working knowledge of matrix
mathematics. If you are interested in learning more about MATLAB but
do not understand matrix mathematics, you may want to attend the IST
minicourse on MATLAB which begins at a more basic level.

1.1 Starting a Session


Before using MATLAB for the first time, we recommend that you create a
subdirectory in your home directory named matlab. Use this directory for
your personal MATLAB function files. See Creating Your Own Func-
tions and Scripts for details. Only once, before you ever use MATLAB at
all, do the following:
mkdir matlab
To actually use MATLAB, do the following:
addpath ‘\matlab’
cd matlab

1.2 Running a MATLAB Demo


If you’ve never seen MATLAB in action before, type demo at the MATLAB
>> prompt:
>> demo
This puts you into the Matlab Expo, which demonstrates, with color
and animation, MATLAB, SIMULINK, and the MATLAB Application Tool-
boxes. From the MATLAB Expo Main Map, you can get introductory infor-
mation about, or ”visit” the various demo modules.

3
2 Matrix/Vector Operations
2.1 Creating and Working with Matrices
The most straightforward way to initialize a matrix is to type a command of
the form:
variable = [value1-1 value1-2 value1-3 ... ; value2-1 value2-2 ...]
where each value may be rational or complex numbers. Within the square
brackets that are used to form vectors and matrices, you can use a semicolon
to end a row. For example:
>> x = [1 2 3 4; 0 9 3 8]
x=
1234
0938
(Note: You can also use the semicolon after an expression or statement
to suppress printing or to separate statements.)
You can also initialize matrices with complex numbers:
>> x = [4+5i 2 4; 1 3+i 7]
x=
4.0000 + 5.0000i 2.0000 4.0000
1.0000 3.0000 + 1.0000i 7.0000
When entering complex numbers as matrix elements within brackets, it
is important to not use blanks. In the example above, the expression 4 +
5i, with the + sign surrounded by blanks, would represent two separate
numbers.
Vectors and scalars are initialized the same way as matrices. It is impor-
tant to note that MATLAB indexes matrices in the following manner:
(1,1) (1,2) (1,3) (1,4)
(2,1) (2,2) (2,3) (2,4)
This means that the first element always has index (1,1), not (0,0).
If x is already defined as a vector of the form [val1 val2 val3 val4...]
then you can define a new variable as a subset of x by using the index of the
specific value in vector x. For example, if x is defined as [2 4 1 7], then:
>> z = x(3)
z=
1
You can specify a value in matrix y the same way:
>> y = [ 1 2 3 4 5; 3 4 5 6 7]

4
y=
12345
34567
>> z = y(2,1)
z=
3
You can also specify a range of numbers in a defined vector or matrix
using the colon operator. The colon causes MATLAB to step in sequence
through the numbers specified. For example,
>> z = (1:5)
z=
12345
So, using the y matrix defined above, you could specify a subset of y
using the colon:
>> z = y(1:2,2:3)
z=
23
45
MATLAB has a variety of built-in functions to make it easier for you
to construct matrices without having to enumerate all the elements. (The
following examples show both vectors and matrices.)
The ones function creates a matrix whose elements are all ones. Typ-
ing ones(m,n) creates an m row by n column matrix of ones. To cre-
ate a ones matrix that is the same size as an existing matric, you can use
ones(size(X )). This does not affect the input argument. For example (this
definition of x applies to subsequent examples in this section):
>> x = [1 2 3 4; 0 9 3 8]
x=
1234
0938
>> y = ones(size(x))
y=
1111
1111
The zeros function is similar to the ones function. Typing zeros(m,n)
creates an m-by-n matrix of zeros, and zeros(size(x)) will create a two-by-
four matrix of zeros, if x is defined the same way as above.

5
The max and min functions return the largest and smallest values in a
vector. For example (this definition of z applies to the following series of
examples):
>> z = [1 2 -9 3 -3 -5]
z=
1 2 -9 3 -3 -5
>> max(z)
ans =
3
If called with a matrix as its argument, max returns a row vector in which
each element is the maximum value of each column of the input matrix. The
max function can also return a second value: the index of the maximum
value in the vector. To get this, assign the result of the call to max to a two
element vector instead of just a single variable.
For example:
>> [a b] = max(z)
a=
3
b=
4
where a is the maximum value of the vector and b is the index of that value.
The MATLAB function min is exactly parallel to max:
>> min(z)
ans =
-9
sum and prod are two more useful functions for matrices. If z is a vector,
sum(z) is the sum of all the elements of the vector z:
>> sum(z)
ans =
-11
For matrices, sum sums the columns. For example:
>> w = magic(3);
>> w
w=
816
357
492
>> sum(w)

6
ans =
15 15 15
>> sum(sum(w))
ans =
45
Similarly, prod(z) is the product of all the elements of z.
>> prod(z)
ans =
-810
Often, it is useful to define a vector as a subunit of a previously defined
vector. To do this, you can use the colon operator. For example, using the z
defined above,
>> z
z=
1 2 -9 3 -3 -5
>> y = z(2:5)
y=
2 -9 3 -3
where (2:5) represents the sequence of index values to be taken from the
larger vector.
The size function returns a two-element vector giving the dimensions of
the matrix with which it was called. For example:
>> x = [1 2 3 4; 0 9 3 8]
x=
1234
0938
>> y = size(x)
y=
24
You can also define the result to be two separate values (as shown in the
max example):
>> [m n] = size(x)
m=
2
n=
4
The length operator returns the length of a vector. If z is defined as in
the above examples,

7
>> length(z)
ans =
6
For matrices, length is the length or the width, whichever is greater, i.e.,
length(z) is equivalent to max(size(z)).

2.2 Basic Arithmetic


MATLAB uses a straight-forward notation for basic scalar arithmetic. The
following table summarizes simple MATLAB notation:
+ addition, - subtraction, * multiplication, / division, ˆ exponentiation
All of these work for two scalars, including complex scalars. You can also
add, subtract, multiply or divide all the elements of a vector or matrix by a
scalar. For example, if x is a matrix or vector, then x+1 adds one to each
element x, and x/2 divides each element of x by 2. xˆ2 does not square each
element of x, but x.ˆ2 does. Matrix and vector exponentiation are discussed
later.
Another useful operator is the colon (:), which you use to specify a range
of numbers (as a vector). For example:
>> x = 1:4
x=
1234
You can optionally give the range indicator a step size as the middle
element in a series of colons. For example:
>> x = 8:-1:5
x=
8765
>> x = 0:0.25:1.25
x=
0 0.25 0.5 0.75 1.0 1.25
The special operator ’ (prime or apostrophe) denotes the transposition of
a matrix. For example:
>> a = [1 2 3]
a=
123
>> a’
ans =
1

8
2
3

2.3 Element-Wise Operations


You often may want to perform an operation on each element of a vector
while doing a computation. For example, you may want to add two vectors by
adding all of the corresponding elements. The addition (+) and subtraction
(-) operators are defined to work on matrices as well as scalars. For example,
if x = [1 2 3] and y = [5 6 2], then
>> w = x+y
w=
685
Multiplying two matrices element by element is a little different. The *
symbol is defined as matrix multiplication when used on two matrices. Use
.* to specify element-wise multiplication. So, using the x and y from above,
>> w = x .* y
w=
5 12 6
You can perform exponentiation on a vector similarly. Typing x .ˆ 2
squares each element of x.
>> w = x .ˆ 2
w=
149
Finally, you cannot use / to divide two matrices element-wise, since /
and \ are reserved for left and right matrix “division.” Instead, you must
use the ./ function. For example:
>> w = y ./ x
w=
5.0000 3.0000 0.6667
All of these operations work for complex numbers as well (the * operator
is no longer required in complex numbers).
The abs operator returns the magnitude of its argument. If applied to a
vector, it returns a vector of the magnitudes of the elements. For example,
if x = [2 -4 3-4i -3i]:
>> y = abs(x)
y=
2453

9
The angle operator returns the phase angle (i.e., the ”argument”) of its
operand in radians. The angle operator can also work element-wise across
a vector. For example:
>> phase = angle(x)
phase=
0 3.1416 -0.9273 -1.5708
The sqrt function computes the square root of its argument. If its argu-
ment is a matrix or vector, it computes the square root of each element. For
example:
>> x
x=
4 −9 i 2 − 2i
>> y = sqrt(x)
y=
2.0000 0 + 3.0000i 0.7071 + 0.7071i 1.5538 − 0.6436i
MATLAB also has operators for taking the real part, imaginary part,
or complex conjugate of a complex number. These functions are real, imag
and conj, respectively. They are defined to work element-wise on any matrix
or vector.
MATLAB has several operators that round fractional numbers to integers.
The round function rounds its argument to the nearest integer. The fix
function rounds its argument to the nearest integer towards zero, e.g. rounds
“down” for positive numbers, and “up” for negative numbers. The floor
function rounds its argument to the nearest integer towards negative infinity,
e.g. “down.” The ceil (short for ceiling) function rounds its argument to the
nearest integer towards positive infinity, e.g. “up.”
round rounds to nearest integer
fix rounds to nearest integer towards zero
floor rounds down (towards negative infinity)
ceil rounds up (towards positive infinity)
All of these commands are defined to work element-wise on matrices and
vectors. If you apply one of them to a complex number, it will round both
the real and imaginary part in the manner indicated. For example:
>> ceil(3.1+2.4i)
ans=
4.0000 + 3.0000i
MATLAB can also calculate the remainder of an integer division opera-
tion. If x = y ∗ n + r, where n is an integer and r is less than n but is not

10
negative, then rem(x,y) is r. For example:
>> x
x=
8 5 11
>> y
y=
653
>> r = rem(x,y)
r=
202
The standard trigonometric operations are all defined as element-wise
operators. The operators sin, cos and tan calculate the sine, cosine and
tangent of their arguments. The arguments to these functions are angles
in radians. Note that the functions are also defined on complex arguments.
For example, cos(x+iy) = cos(x)cosh(y) - i sin(x)sinh(y). The inverse trig
functions (acos, asin and atan) are also defined to operate element-wise
across matrices. Again, these are defined on complex numbers, which can
lead to problems for the incautious user. The arctangent is defined to return
angles between pi/2 and -pi/2.
In addition to the primary interval arctangent discussed above, MATLAB
has a full four-quadrant arctangent operator, atan2. atan2(y,x) returns the
angle between -pi and pi whose tangent is the real part ofy/x. Ifx andy are
vectors, atan2(y,x) dividesy byxelement-wise, then returns a vector in which
each element is the four-quadrant arctangent of corresponding element of the
y/x vector.
MATLAB also includes functions for exponentials and logarithms. The
exp operator computes e to the power of its argument. This works element-
wise, and on complex numbers. The pi function returns the floating point
number nearest the value of pi. So, to generate the complex exponential with
a frequency of pi/4, we could type:
>> n = 0:7;
>> s = exp(i*(pi/4)*n)
s=
Columns 1 through 4
1.00 0.7071+0.7071i 0.00+1.0000i -0.7071+0.7071i
Columns 5 through 8
-1.0000 + 0.0000i -0.7071 - 0.7071i -0.0000 - 1.0000i 0.7071 - 0.7071i

11
MATLAB also has natural and base-10 logarithms. The log function
calculates natural logs, and log10 calculates base-10 logs. Both operate
element-wise for vectors. Both are defined for complex values.

2.4 Logical Operations


MATLAB allows you to perform boolean operations on vectors element-wise.
For the purpose of boolean algebra, MATLAB regards anything with a non-
zero real part as true, and everything else as as false. MATLAB uses & for
the boolean and operator, | for or, and ∼ for not. For example:
>> x = [1 0 2 4] & [0 0 1 i]
x=
0010
>> x = [1 0 2 4] | [0 0 1 i]
x=
1011
In addition, you can run a cumulative boolean ”or” or boolean ”and”
across all the elements of a matrix or vector. If v is a vector or matrix,
any(v) returns true if the real part of any element of v is non-zero; all(v)
returns true if all the elements of vhave non-zero real parts.
You can also compare two vectors element-wise with any of six basic
relational operators:
< less than
> greater than
== equal to
∼= not equal to
<= less than or equal to
>= greater than or equal to
For example:
>> x = [1 2 3 4 5] <= [5 4 3 2 1]
x=
11100
Relational operators are particularly important in programming control
structures.

12
2.5 Selective Indexing
Sometimes, you only want to perform an operation on certain elements of a
vector, such as all the elements of the vector that are less than 0. One way
to do this is a for loop that checks to see whether each element is less than
zero, and if so, does the appropriate function. However, MATLAB includes
another way to do this. If you say
>> x(x<0) = - x(x<0)
MATLAB changes all the negative elements of the vector x to be positive.
The following sequence of commands illustrates this:
>> x = [-3 -2 0 2 4]
x=
-3 -2 0 2 4
>> x(x<0) = - x(x<0)
x=
32024
Though this notation can be more confusing than a for loop, MATLAB
is written such that this operation executes much, much faster than the
equivalent for loop.
You can also perform operations on a vector conditionally based upon
the value of the corresponding element of another vector. For example, if
you want to divide two vectors element-wise, you have to worry about what
happens if the denominator vector includes zeros. One way to deal with this
is shown below.
>> x = [3 2 0 2 4]
x=
32024
>> y = [1 1 1 1 1]
y=
11111
>> q = zeros(1,length(y))
q=
00000
>> q(x∼=0) = y(x∼=0) ./ x(x∼=0)
q=
0.3333 0.5000 0 0.5000 0.2500
You can perform this type of conditional indexing with any boolean op-
erator discussed earlier, or even with boolean operators on the results of

13
functions on elements of vectors. For example:
>> q((x<=3) & (q<=0.4)) = q((x<=3) & (q<=0.4)) + 14
q=
14.3333 0.5000 0 0.5000 0.2500

2.6 Polynomial Operations


Vectors can also be used to represent polynomials. If you want to represent
an Nth-order polynomial, you use a length N+1 vector where the elements are
the coefficients of the polynomial arranged in descending order of exponent.
So, to define y = xˆ2 - 5x + 6, you would type:
>> y = [1 -5 6];
The MATLAB roots function calculates the roots of a polynomial for
you. If y is defined as above:
>> roots(y)
ans =
3
2
MATLAB also has the poly function, which takes a vector and returns
the polynomial whose roots are the elements of that vector.
You can multiply two polynomials using the conv function. The convo-
lution of the coefficient vectors is equivalent to multiplying the polynomials.
For example, if we define w = 3xˆ2 - 4x -1 (so the vector x = [3 -4 -1]) and
use the y given above:
>> z = conv(w,y)
z=
3 -19 37 -19 -6
The polyval function returns the value of a polynomial at a specific point.
For example:
>> polyval(y,1)
ans =
2
The polyval function also works element-wise across a vector of points,
returning the vector where each element is the value of the polynomial at the
corresponding element of the input vector.

14
2.7 Libraries and Search Paths
MATLAB has several libraries that contain files of functions called M-files.
An M-file consists of a sequence of MATLAB statements (see Creating Your
Own Functions). To see the complete list of libraries, type the command
path at the MATLAB >> prompt.
The list you get with the path command is also MATLAB’s current
directory search path. MATLAB’s search rules are as follows; when you
enter a name, MATLAB:
1. Looks to see if the name is a variable.
2. Looks for it as a built-in function.
3. Searches in the current directory for the related .m file.
4. Searches the directories specified by path for the .m file.
You can also use path, with appropriate arguments, to add or change
directories in the search path. For details, type help path at the MATLAB
>> prompt, or see path in the MATLAB Reference Guide.

3 Graphics
MATLAB supports several commands that allow you to display results of
your computations graphically. Graphs are displayed in a graphics window
that MATLAB creates when you give one of the plotting commands. The
default graphics window starts up with a black background. To change this,
before issuing any plotting commands, type the command whitebg at the
MATLAB >> prompt.

3.1 Plotting Individual Graphs


The plot command is the simplest way of graphing data. If x is a vector,
plot(x) will plot the elements of x against their indices. The adjacent val-
ues of xwill be connected by lines. For example, to plot the discrete-time
sequence that is a sinusoid of frequency pi/6, you would type:
>> n = 0:11;
>> y = sin((pi/6)*n);
>> plot(n,y)
When plot gets two vectors for arguments, it creates a graph with the first
argument as the abscissa values, and the second vector as ordinate values.

15
In the example above, plot will use the values of y for the y-axis, and the
values of n for the x-axis. If you typed:
>> plot(y)
MATLAB would use the values of y for the y-axis and their indices for
the x-axis. Notice that the first value graphed would have an abscissa value
of one, and not zero. This is because MATLAB indexes vector elements
beginning with one, not zero.
You can also change the type of line used to connect the points by includ-
ing a third argument specifying line type. The format for this is plot(x,y,line-
type). The line types available are:
’-’ solid line (default)
’–’ dashed line
’:’ dotted line
’-.’ line of alternating dots and dashes
Whichever character you chose to use must be enclosed by single quotes.
For example, plot(n,y,’:’) would create the same graph as above, except
that the points would be connected by a dotted line. The default line type
is solid. In this case, it is misleading to connect the adjacent values by lines,
since this is a graph of a discrete-time sequence. Instead, we should just put
a mark to indicate each sample value. We can do this by using a different set
of characters in place of the line-type argument. If we use a ’.’, each sample
is marked by a point. Using a ’+’ marks each sample with a + sign, ’*’ uses
stars, ’o’ uses circles, and ’x’ uses x’s. For example, the following command
plots the values of y against their indices, marking each sample with a circle:
>> plot(n,y,’o’)
You can also plot several graphs on the same axis. For example, the
following command plots y1 versus x1 and y2 versus x2 on the same axis
using different line types for each graph:
plot(x1,y1,x2,y2)
You can also include a specific line or point type (from the list above) for
each graph:
plot(x1,y1,’line-type1 ’,x2,y2,’line-type2 ’)
You can use additional MATLAB commands to title your graphs or put
text labels on your axes. For example, the following command labels the
current graph at the top with the text enclosed in single quotes:
>> title(’MATLAB Graph # 1’)
Similarly, the following commands label the x- and y-axes:
>> xlabel(’This is the x-axis’)

16
>> ylabel(’This is the y-axis’)
The axis command is used to control the limits and scaling of the current
graph. Typing
[min-x max-x min-y max-y] = axis
will assign a four-element vector to a that sets the “minimum ranges” for the
axes. The first element is the minimum x-value, the second is the maximum x-
value for the current graph. The third and fourth elements are the minimum
and maximum y-values, respectively. You can set the values of the axes by
calling the axis function with a four-element vector for an argument. You
might want to do this, for example, if you were going to plot several sets of
data on the same graph and you knew that the range of one set of data was
significantly larger than the other.
The elements of the vector you use to set the values of the axes should
be your choices for the x- and y-axis limits, in the same order as specified
above ([x-min x-max y-min y-max]). So, if you type
>> axis([-10 10 -5 5])
you will rescale the axis in the graphics window so the x-axis goes at least
from -10 to 10, and the y-axis from -5 to 5. The axis command can be
stubborn, and may expand your limits to larger limits it finds easier to draw.
There is unfortunately little you can do about this.
The hold command will keep the current plot and axes even if you plot
another graph. The new graph will just be put on the current axes (as much
as fits). Typing hold a second time will toggle the hold off again, so the
screen will clear and rescale for the next graph.

3.2 Plotting Multiple Graphs


You can use the subplot command to split the screen into multiple windows,
and then select one of the sub-windows as active for the next graph. The
subplot function can divide the graphics window into a maximum of four
quadrants; first the window splits horizontally, then it splits vertically. The
format of the command is:
>> subplot(xyn)
In this command, x is the number of vertical divisions, y is the number
of horizontal divisions, and n is the window to select for the first plot. Both
x and y must be less than or equal to two, and n must be less than or equal
tox times y. For example, subplot(121) will create two full-height, half-
width windows for graphs, and select the first, e.g. left, window as active for

17
the first graph. After that, unless you specifically indicate which window is
active, MATLAB cycles through them with each successive plot.

3.3 Output of Plots and Graphs


3.3.1 Formatting Plots to Copy/Paste Operations
Matlab plots can be copied to documents (such as word documents) using
common COPY (Ctrl+C)/PASTE (Ctrl+V) clipboard operations. Copy/Paste
settings can be modified on the File¿Preferences¿Copying Options. There are
two formats: copy as bitmap / copy as metafile. The first one copy the plot
as it appears in the screen. Copying as metafile will copy only the plot.
The size of the plot to be inserted on a third party document can be
defined (in centimeters):
set(get(gcf,’currentaxes’),’units’,’centimeters’,’position’,[left top width height]);

4 Saving Your Work


If you want to save all your variables and their current values, type:
>> save filename
before you exit MATLAB, and your work will be saved in a file named file-
name.mat (default filename matlab.mat). If you only want to save some of
the variables, you can give the save command the names of the variables to
save. If you type:
>> save filename x y
MATLAB will save just the variables x and y in the file filename.mat.
When you start up MATLAB at some future time, you can restore all
your variables from the file filename.mat by typing:
>> load filename
The command load, by itself, loads all the variables saved in matlab.mat.
A file with the extension .mat is assumed to be binary MATLAB format.
To retrieve the variables from filename.mat, the command is:
load filename
A file with any other extension is assumed to be ASCII. To load an ASCII
file that does not have an extension, or if the ASCII file has an extension of
.mat, use the command:
load filename -ascii

18
5 Interface Controls
5.1 Controlling the MATLAB Session
The following table briefly describes the interface controls available to you
when using MATLAB:
clc clear the command window
clear x clear variable x
clf clear the graphics window
diary record transcript of session (specify a file-
name)
load load previously saved workspace or session
save save current workspace or session (using mat-
lab.mat as default filename)
who list defined variables
whos list defined variable with additional infor-
mation
When you first start running MATLAB, it is case-sensitive. This means
that MATLAB distinguishes between uppercase and lowercase variable and
function names, just as Athena’s operating system does. So, you can safely
have two separate variables named g and G. If this is the way you want MAT-
LAB to operate, then you never have to bother with the casesen command.
If you want MATLAB to be non-case-sensitive, then you must type casesen
at the beginning of each MATLAB session.
MATLAB allows you to clear either the command (text) window, or the
graphics window. The clc command clears the command window, and give
you a fresh >> prompt. The clf command clears the graphics window and
leaves it blank.
The who command displays the names of all your variables. The whos
command gives you the names of all the variables, along with information
about each variable’s size, number of elements, number of bytes, density, and
whether the variable is complex. For example:
” whos
Name Size Bytes Class
a 100x200 160000 double array
b 100x100 80000 double array
Grand total is 30000 elements using 240000 bytes

19
If you run the who command and see that you have variables you are
no longer using, use the clear command to remove obsolete variables. For
example, typing clear z would delete the variable z.
MATLAB’s diary command records your session in a transcript file that
you specify. Typing diary filename starts recording all the commands you
type in filename, including ”most of the resulting output” (according to the
MATLAB manual). Graphs are not recorded, but almost all printed results
are. Typing diary off turns the transcript off, and diary on turns it back
on. The file is created in ASCII format, suitable for editing with Emacs and
including in other reports. In fact, this function was used to generate almost
all the examples in this document.

5.2 Working With the Operating System


MATLAB also defines some basic file manipulation utilities, to work with
the operating system without having to quit and restart MATLAB:
cd change directory (same as chdir )
delete delete file (same as rm)
dir list (same as ls)
ls list (same as dir )
type display contents of a file (same as cat)
dos execute operating system command and return
result to MATLAB
! precedes operating system command called within
MATLAB
The command unix can be used to execute any operating system com-
mand and return the result to MATLAB. For example:
>> [s,date] = dos(’date’)
s=0
date = SAT Jan 27 11:05:12 EDT 2001
You can use any real operating system command by preceding it by a !.
Thus, typing !date gives you the current date and time. All pathnames and
wildcards should work just as they do at your dos prompt.

20
6 For More Help about MATLAB
6.1 Online Help
MATLAB has a good built-in help facility. Typing help with no arguments
at the MATLAB >> prompt displays a list of all primary help topics, by
directory in the MATLABPATH, along with a short description for each one.
Typing help directoryname displays a list of .m files in the directory, along
with a brief description of each one.
Typing help function displays the syntax for the function (i.e. what
arguments it expects) and a short description of what that function does. If
you think you are doing everything right, but MATLAB claims you are in
error, try looking at the help for the functions you are using.
A new command, lookfor xyz , searches for the string xyz in the first
comment line of help text in all M-files in the MATLABPATH. Because
lookfor must look at a lot of files, be ready for the search to take a minute
or so.
When you write your own functions, you can also include help informa-
tion for them. This can be very useful for other people using your function,
or for your own use if you haven’t used the function for a while. For more
information on how to include help information for your own functions, see
the section Functions.
Typing helpdesk’ll launch matlab help system (html documentation).

7 Matrix building functions.


Convenient matrix building functions are:

• eye identity matrix


• zeros matrix of zeros
• ones matrix of ones
• diag create or extract diagonals
• triu upper triangular part of a matrix
• tril lower triangular part of a matrix

21
• rand randomly generated matrix

• hilb Hilbert matrix

• magic magic square

• toeplitz see help toeplitz

For example, zeros(m,n) produces an m-by-n matrix of zeros and zeros(n)


produces an n-by-n one. If A is a matrix, then zeros(size(A)) produces a
matrix of zeros having the same size as A.
If x is a vector, diag(x) is the diagonal matrix with x down the diagonal;
if A is a square matrix, then diag(A) is a vector consisting of the diagonal of
A. What is diag(diag(A))? Try it.
Matrices can be built from blocks. For example, if A is a 3-by-3 matrix,
then:

B = [A, zeros(3,2); zeros(2,3), eye(2)]

will build a certain 5-by-5 matrix. Try it.

8 For, while, if and relations.


In their basic forms, these MATLAB flow control statements operate like
those in most computer languages.

8.1 For.
For example, for a given n, the statement

x = []; for i = 1:n, x=[x,iˆ2], end

or

x = [];
for i = 1:n
x = [x,i^2]
end

22
will produce a certain n-vector and the statement:

x = []; for i = n:-1:1, x=[x,iˆ2], end

will produce the same vector in reverse order. Try them. Note that a matrix
may be empty (such as x = []). The statements:

for i = 1:m
for j = 1:n
H(i, j) = 1/(i+j-1);
end
end
H

will produce and print to the screen the m-by-n hilbert matrix. The semicolon
on the inner statement is essential to suppress printing of unwanted inter-
mediate results while the last H displays the final result. The for statement
permits any matrix to be used instead of 1:n. The variable just consecutively
assumes the value of each column of the matrix. For example:

s = 0;
for c = A
s = s + sum(c);
end

computes the sum of all entries of the matrix A by adding its column sums
(Of course, sum(sum(A)) does it more eficiently; see section ). In fact, since
1:n = [1,2,3,: : : ,n], this column-by-column assigment is what occurs with:
”if i = 1:n,. . . ”

8.2 While.
The general form of a while loop is:

while relation
statements
end

23
The statements will be repeatedly executed as long as the relation remains
true. For example, for a given number a, the following will compute and
display the smallest nonnegative integer n such that 2n ≥ a:

n = 0;
while 2^n < a
n = n + 1;
end
n

8.3 If.
The general form of a simple if statement is:

if relation
statements
end

The statements will be executed only if the relation is true. Multiple branch-
ing is also possible, as is illustrated by:

if n < 0
parity = 0;
elseif rem(n,2) == 0
parity = 2;
else
parity = 1;
end

In two-way branching the elseif portion would, of course, be omitted.

8.4 Relations.
The relational operators in MATLAB are:

• < less than

• > greater than

24
• <= less than or equal

• >= greater than or equal

• == equal

• ∼= not equal.

Note that “=” is used in an assignment statement while “==” is used in a


relation. Relations may be connected or quantified by the logical operators:

• & and

• | or

• ∼ not

When applied to scalars, a relation is actually the scalar 1 or 0 depending


on whether the relation is true or false. Try entering 3 < 5, 3 > 5, 3 ==
5, and 3 == 3. When applied to matrices of the same size, a relation is a
matrix of 0’s and 1’s giving the value of the relation between corresponding
entries. Try a = rand(5), b = triu(a), a == b. A relation between matrices
is interpreted by while and if to be true if each entry of the relation matrix
is nonzero. Hence, if you wish to execute statement when matrices A and B
are equal you could type:

if A == B
statement
end

but if you wish to execute statement when A and B are not equal, you would
type:

if any(any(A ~= B))
statement
end

or, more simply,

25
if A == B
else
statement
end

Note that the seemingly obvious:


if A ~= B
statement
end
will not give what is intended since statement would execute only if each of
the corresponding entries of A and B differ. The functions any and all can
be creatively used to reduce matrix relations to vectors or scalars. Two any’s
are required above since any is a vector operator (see section 8).

9 Scalar functions.
Certain MATLAB functions operate essentially on scalars, but operate element-
wise when applied to a matrix. The most common such functions are:

sin asin exp abs round


cos acos log (natural log) sqrt floor
tan atan rem (remainder) sign ceil

10 Vector functions.
Other MATLAB functions operate essentially on a vector (row or column),
but act on an m-by-n matrix (m ≥ 2) in a column-by-column fashion to pro-
duce a row vector containing the results of their application to each column.
Row-by-row action can be obtained by using the transpose; for example,
mean(A’)’. A few of these functions are:

max sum median any min prod mean all sort std

For example, the maximum entry in a matrix A is given by max(max(A))


rather than max(A). Try it.

26
11 Matrix functions.
Much of MATLAB’s power comes from its matrix functions. The most useful
ones are:

• eig eigenvalues and eigenvectors

• chol cholesky factorization

• svd singular value decomposition

• inv inverse

• lu LU factorization

• qr QR factorization

• hess hessenberg form

• schur schur decomposition

• rref reduced row echelon form

• expm matrix exponential

• sqrtm matrix square root

• poly characteristic polynomial

• det determinant

• size size of a matrix

• norm 1-norm, 2-norm, F-norm

• cond condition number in the 2-norm

• rank rank

27
MATLAB functions may have single or multiple output arguments. For
example:

y = eig(A), or simply eig(A)

produces a column vector containing the eigenvalues of A while:

[U,D] = eig(A)

produces a matrix U whose columns are the eigenvectors of A and a diagonal


matrix D with the eigenvalues of A on its diagonal. Try it.

12 Command line editing and recall.


The command line in MATLAB can be easily edited. The cursor can be
positioned with the left/right arrows and the Backspace (or Delete) key used
to delete the character to the left of the cursor. Other editing features are
also available. On a PC try the Home, End, and Delete keys; A convenient
feature is use of the up/down arrows to scroll through the stack of previous
commands. One can, therefore, recall a previous command line, edit it, and
execute the revised command line. For small routines, this is much more
convenient that using an M-file which requires moving between MATLAB
and the editor.
For example, flopcounts for computing the inverse of matrices of various
sizes could be compared by repeatedly recalling, editing, and executing

a = rand(8); flops(0), inv(a); flops

If one wanted to compare plots of the functions y = sin mx and y = sin


nx on the interval [0; 2] for various m and n, one might do the same for the
command line:

m=2; n=3; x=0:.01:2*pi; y=sin(m*x); z=cos(n*x); plot(x,y,x,z)

Try it..

28
13 Submatrices and colon notation.
Vectors and submatrices are often used in MATLAB to achieve fairly complex
data manipulation effects. “Colon notation” (which is used both to generate
vectors and reference submatrices) and subscripting by integral vectors are
keys to efficient manipulation of these objects. Creative use of these features
to vectorize operations permits one to minimize the use of loops (which slows
MATLAB) and to make code simple and readable.
Special effort should be made to become familiar with them.
The expression 1:5 (met earlier in for statements) is actually the row vec-
tor [1 2 3 4 5]. The numbers need not be integers nor the increment one. For
example:

0.2:0.2:1.2

gives [0.2, 0.4, 0.6, 0.8, 1.0, 1.2], and

5:-1:1

gives [5 4 3 2 1].

The following statements will, for example, generate a table of sines. Try it.

x = [0.0:0.1:2.0]’;y = sin(x); [x y]

Note that since sin operates entry-wise, it produces a vector y from the
vector x. The colon notation can be used to access submatrices of a matrix.
For example:

A(1:4,3) is the column vector consisting of the first four entries of the
third column of A.

A colon by itself denotes an entire row or column: A(:,3) is the third


column of A, and A(1:4,:) is the first four rows.

Arbitrary integral vectors can be used as subscripts: A(:,[2 4]) contains


as columns, columns 2 and 4 of A.

29
Such subscripting can be used on both sides of an assignment statement:
A(:,[2 4 5]) = B(:,1:3) replaces columns 2,4,5 of A with the first three columns
of B. Note that the entire altered matrix A is printed and assigned. Try it.

Columns 2 and 4 of A can be multiplied on the right by the 2-by-2 matrix


[1 2;3 4]:

A(:,[2,4]) = A(:,[2,4])*[1 2;3 4] Once again, the entire altered matrix is


printed and assigned.

If x is an n-vector, what is the effect of the statement x = x(n:-1:1)? Try it.

Also try: y = fliplr(x) and y = flipud(x’).

To appreciate the usefulness of these features, compare these MATLAB


statements with a Pascal, FORTRAN, or C routine to effect the same.

14 M-files.
MATLAB can execute a sequence of statements stored in diskfiles. Such
files are called “M-files” because they must have the file type of “.m” as the
last part of their filename. Much of your work with MATLAB will be in
creating and running M-files. M-files are usually created using your local
editor. There are two types of M-files: script files and function files.

14.1 Script files.


A script file consists of a sequence of normal MATLAB statements. If the
file has the filename, say, rotate.m, then the MATLAB command rotate will
cause the statements in the file to be executed. Variables in a script file
are global and will change the value of variables of the same name in the
environment of the current MATLAB session.
Script files may be used to enter data into a large matrix; in such a file,
entry errors can be easily corrected. If, for example, one enters in a diskfile
data.m
A = [ 1 2 3 4;5 6 7 8 ];

30
then the MATLAB statement data will cause the assignment given in data.m
to be carried out.
However, it is usually easier to use the MATLAB function load. An M-file
can reference other M-files, including referencing itself recursively.

14.2 Function files.


Function files provide extensibility to MATLAB. You can create new func-
tions specific to your problem which will then have the same status as other
MATLAB functions. Variables in a function file are by default local. A
variable can, however, be declared global (see help global).
We first illustrate with a simple example of a function file.

function a = randint(m,n)
% RANDINT Randomly generated integral matrix.
% randint(m,n) returns an m-by-n such matrix with entries
% between 0 and 9.
a = floor(10*rand(m,n));

A more general version of this function is the following:

function a = randint(m,n,a,b)
% RANDINT Randomly generated integral matrix.
% randint(m,n) returns an m-by-n such matrix with entries
% between 0 and 9.
% rand(m,n,a,b) return entries between integers a and b.
if nargin < 3
a = 0;
b = 9;
end
a = floor((b-a+1)*rand(m,n)) + a;

This should be placed in a diskfile with filename randint.m (correspond-


ing to the function name). The first line declares the function name, input
arguments, and output arguments; without this line the file would be a script
file. Then a MATLAB statement:

z = randint(4,5)

31
for example, will cause the numbers 4 and 5 to be passed to the variables
m and n in the function file with the output result being passed out to
the variable z. Since variables in a function file are local, their names are
independent of those in the current MATLAB environment.
Note that use of nargin (“number of input arguments”) permits one to set
a default value of an omitted input variable–such as a and b in the example.
A function may also have multiple output arguments. For example:

function [mean, stdev] = stat(x)


% STAT Mean and standard deviation
% For a vector x, stat(x) returns the mean of x;
% [mean, stdev] = stat(x) both the mean and standard deviation.
% For a matrix x, stat(x) acts columnwise.
[m n] = size(x);
if m == 1
m = n; % handle case of a row vector
end
mean = sum(x)/m;
stdev = sqrt(sum(x.^2)/m - mean.^2);

Once this is placed in a diskfile stat.m, a MATLAB command:

[xm, xd] = stat(x)

for example, will assign the mean and standard deviation of the entries in
the vector x to xm and xd, respectively. Single assignments can also be made
with a function having multiple output arguments. For example,

xm = stat(x)

(no brackets needed around xm) will assign the mean of x to xm.
The % symbol indicates that the rest of the line is a comment; MATLAB
will ignore the rest of the line. Moreover, the first few contiguous comment
lines, which document the M-file, are available to the on-line help facility and
will be displayed if, for example, help stat is entered. Such documentation
should always be included in a function file.
This function illustrates some of the MATLAB features that can be used
to produce eficient code.

32
Note, for example, that x.ˆ2 is the matrix of squares of the entries of x,
that sum is a vector function, that sqrt is a scalar function, and that the
division in sum(x)/m is a matrix-scalar operation. Thus all operations are
vectorized and loops avoided.
If you can’t vectorize some computations, you can make your for loops go
faster by preallocating any vectors or matrices in which output is stored. For
example, by including the second statement below, which uses the function
zeros, space for storing E in memory is preallocated. Without this MATLAB
must resize E one column larger in each iteration, slowing execution.

M = magic(6);
E = zeros(6,50);
for j = 1:50
E(:,j) = eig(M\^{}i);
end

Some more advanced features are illustrated by the following function.


As noted earlier, some of the input arguments of a function–such as tol in
this example, may be made optional through use of nargin (“number of input
arguments”). The variable nargout can be similarly used. Note that the fact
that a relation is a number (1 when true; 0 when false) is used and that,
when while or if evaluates a relation, “nonzero” means “true” and 0 means
“false”.
Finally, the MATLAB function feval permits one to have as an input
variable a string naming another function. (Also see eval.)

function [b, steps] = bisect(fun, x, tol)


% BISECT Zero of a function of one variable via the bisection method.
% bisect(fun,x) returns a zero of the function. fun is a string
% containing the name of a real-valued MATLAB function of a
% single real variable; ordinarily functions are defined in
% M-files. x is a starting guess. The value returned is near
% a point where fun changes sign. For example,
% bisect(’sin’,3) is pi. Note the quotes around sin.
%
% An optional third input argument sets a tolerence for the
% relative accuracy of the result. The default is eps.
% An optional second output argument gives a matrix containing a

33
% trace of the steps; the rows are of form [c f(c)].

% Initialization
if nargin < 3
tol = eps;
end
trace = (nargout == 2);
if x ~= 0
dx = x/20;
else
dx = 1/20;
end
a = x - dx;
fa = feval(fun,a);
b = x + dx;
fb = feval(fun,b);
% Find change of sign.
while (fa > 0) == (fb > 0)
dx = 2.0*dx;
a = x - dx;
fa = feval(fun,a);
if (fa > 0) ~= (fb > 0)
break
end
b = x + dx;
fb = feval(fun,b);
end
if trace
steps = [a fa; b fb];
end
% Main loop
while abs(b - a) > 2.0*tol*max(abs(b),1.0)
c = a + 0.5*(b - a);
fc = feval(fun,c);
if trace
steps = [steps; [c fc]];
end

34
if (fb > 0) == (fc > 0)
b = c; fb = fc;
else
a = c; fa = fc;
end
end

Some of MATLAB’s functions are built-in while others are distributed


as M-files. The actual listing of any non-built-in M-file–MATLAB’s or your
own–can be viewed with the MATLAB command edit functionname.
Try entering edit eig, edit vander, and edit rank.

15 Text strings, error messages, input.


Text strings are entered into MATLAB surrounded by single quotes. For
example:

s = ’This is a test’

assigns the given text string to the variable s. Text strings can be displayed
with the function disp. For example:

disp(’this message is hereby displayed’)

Error messages are best displayed with the function error:

error(’Sorry, the matrix must be symmetric’)

since when placed in an M-File, it aborts execution of the M-File.


In an M-file the user can be prompted to interactively enter input data
with the function input. When, for example, the statement:

iter = input(’Enter the number of iterations: ’);

is encountered, the prompt message is displayed and execution pauses while


the user keys in the input data. Upon pressing the return key, the data is
assigned to the variable iter and execution resumes.

35
16 Managing M-files.
While using MATLAB one frequently wishes to create or edit an M-file with
the local editor and then return to MATLAB. One wishes to keep MATLAB
active while editing a file since otherwise all variables would be lost upon
exiting.
This can be easily done using the !-feature. If, while in MATLAB, you pre-
cede it with an !, any system command – such as those for editing, printing,
or copying a file–can be executed without exiting MATLAB. If, for example,
the system command notepad accesses your editor, the MATLAB command:

>> !notepad rotate.m

will let you edit the file named rotate.m using your local editor. Upon leaving
the editor, you will be returned to MATLAB just where you left it.
MATLAB also have a m-file editor which can be used has a edit to build
the m-files. This editor can be accessed directly by using the command edit.
M-files must be in a directory accessible to MATLAB. M-files in the
present working directory are always accessible. On most mainframe or work-
station network installations, personal M-files which are stored in a subdirec-
tory of one’s home directory named matlab will be accessible to MATLAB
from any directory in which one is working. The current list of directories in
MATLAB’s search path is obtained by the command path.
This command can also be used to add or delete directories from the
search path. See help path.

17 Graphics.
MATLAB can produce planar plots of curves, 3-D plots of curves, 3-D mesh
surface plots, and 3-D faceted surface plots. The primary commands for
these facilities are plot, plot3, mesh, and surf, respectively. An introduction
to each of these is given below.
To preview some of these capabilities, enter the command demo and select
some of the graphics options.

36
17.1 Planar plots.
The plot command creates linear x-y plots; if x and y are vectors of the same
length, the command plot(x,y) opens a graphics window and draws an x-y
plot of the elements of x versus the elements of y. You can, for example,
draw the graph of the sine function over the interval -4 to 4 with the follow-
ing commands:

x = -4:.01:4; y = sin(x); plot(x,y)

Try it.
The vector x is a partition of the domain with meshsize 0.01 while y is a
vector giving the values of sine at the nodes of this partition (recall that sin
operates entrywise).
You will usually want to keep the current graphics window (“figure”)
exposed – but moved to the side – and the command window active.
One can have several graphics figures, one of which will at any time
be the designated “current” figure where graphs from subsequent plotting
commands will be placed. If, for example, figure 1 is the current figure,
then the command figure(2) (or simply figure) will open a second figure (if
necessary) and make it the current figure.
The command figure(1) will then expose figure 1 and make it again the
current figure. The command gcf will return the number of the current figure.
2
As a second example, you can draw the graph of y = ex over the interval
-1.5 to 1.5 as follows:

x = -1.5:.01:1.5; y = exp(-x.ˆ2); plot(x,y)

Note that one must precede ˆ by a period to ensure that it operates entrywise.
MATLAB supplies a function fplot to easily and efciently plot the graph
of a function.
For example, to plot the graph of the function above, one can first define
the function in an M-file called, say, expnormal.m containing:

function y = expnormal(x)
y = exp(-x.^2);

Then the command:

37
fplot(’expnormal’, [-1.5,1.5])

will produce the graph. Try it.


Plots of parametrically defined curves can also be made. Try, for example:

t=0:.001:2*pi; x=cos(3*t); y=sin(2*t); plot(x,y)

The graphs can be given titles, axes labeled, and text placed within the graph
with the following commands which take a string as an argument.

• title graph title

• xlabel x-axis label

• ylabel y-axis label

• gtext place text on the graph using the mouse

• text position text at specied coordinates

For example, the command:

title(’Best Least Squares Fit’)

gives a graph a title. The command gtext(’The Spot’) allows one to interac-
tively place the designated text on the current graph by placing the mouse
pointer at the desired position and clicking the mouse. To place text in a
graph at designated coordinates, one would use the command text (see help
text).
The command grid will place grid lines on the current graph. By default,
the axes are auto-scaled. This can be overridden by the command axis. Some
features of axis are:

• axis([x min ,xmax,y min ,ymax]) set axis scaling to pre-


scribed limits

• axis(axis) freezes scaling for subsequent graphs

• axis auto returns to auto-scaling

• v = axis returns vector v showing current scaling

38
• axis square same scale on both axes

• axis equal same scale and tic marks on both axes

• axis off turns off axis scaling and tic marks

• axis on turns on axis scaling and tic marks

The axis command should be given after the plot command.


Two ways to make multiple plots on a single graph are illustrated by:

x=0:.01:2*pi;y1=sin(x);y2=sin(2*x);y3=sin(4*x);plot(x,y1,x,y2,x,y3)

and by forming a matrix Y containing the functional values as columns

x=0:.01:2*pi; Y=[sin(x)’, sin(2*x)’, sin(4*x)’]; plot(x,Y)

Another way is with hold. The command hold on freezes the current graph-
ics screen so that subsequent plots are superimposed on it. The axes may,
however, become rescaled. Entering hold off releases the “hold.”
One can override the default linetypes, pointtypes and colors. For exam-
ple:

x=0:.01:2*pi; y1=sin(x); y2=sin(2*x); y3=sin(4*x); plot(x,y1,’–’,x,y2,’:’,x,y3,’+’)

renders a dashed line and dotted line for the first two graphs while for the
third the symbol + is placed at each node. The line- and mark-types are:

• Linetypes: solid (-), dashed (–). dotted (:), dashdot (-.)

• Marktypes: point (.), plus (+), star (*), circle (o), x-mark
(x)

Colors can be specied for the line- and mark-types:

Colors: yellow (y), magenta (m), cyan (c), red (r) green (g), blue (b),
white (w), black(k)

For example, plot(x,y,’r–’) plots a red dashed line.

39
The command subplot can be used to partition the screen so that several
small plots can be placed in one figure. See help subplot.
Other specialized 2-D plotting functions you may wish to explore via help
are: polar, bar, hist, quiver, compass, feather, rose, stairs, fill

17.2 Graphics hardcopy


A hardcopy of the current graphics figure can be most easily obtained with
the MATLAB command print. Entered by itself, it will send a high-resolution
copy of the current graphics figure to the default printer.
The printopt M-file is used to specify the default setting used by the print
command.
If desired, one can change the defaults by editing this file (see help print-
opt). The command print filename saves the current graphics figure to the
designated filename in the default file format. If filename has no extension,
then an appropriate extension such as .ps, .eps, or .jet is appended. If, for
example, PostScript is the default file format, then

print lissajous

will create a PostScript file lissajous.ps of the current graphics figure which
can subsequently be printed using the system print command. If filename
already exists, it will be overwritten unless you use the -append option. The
command:

print -append lissajous

will append the (hopefully different) current graphics figure to the existing
file lissajous.ps. In this way one can save several graphics figures in a single
file.
The default settings can, of course, be overwritten. For example:

print -deps -f3 saddle

will save to an Encapsulated PostScript file saddle.eps the graphics figure 3


– even if it is not the current figure.

40
17.3 3-D line plots.
Completely analogous to plot in two dimensions, the command plot3 pro-
duces curves in three dimensional space. If x, y, and z are three vectors of
the same size, then the command plot3(x,y,z) will produce a perspective plot
of the piecewise linear curve in 3-space passing through the points whose co-
ordinates are the respective elements of x, y, and z. These vectors are usually
defined parametrically. For example:

t=.01:.01:20*pi; x=cos(t); y=sin(t); z=t.b 3; plot3(x,y,z)

will produce a helix which is compressed near the x-y plane (a “slinky”). Try
it.
Just as for planar plots, a title and axis labels (including zlabel) can
be added. The features of axis command described there also hold for 3-D
plots; setting the axis scaling to prescribed limits will, of course, now require
a 6-vector.

17.4 3-D mesh and surface plots.


Three dimensional wire mesh surface plots are drawn with the command
mesh. The command mesh(z) creates a three-dimensional perspective plot of
the elements of the matrix z. The mesh surface is defined by the z-coordinates
of points above a rectangular grid in the x-y plane. Try mesh(eye(10)).

Similarly, three dimensional faceted surface plots are drawn with the com-
mand surf. Try surf(eye(10)).

To draw the graph of a function z = f(x; y) over a rectangle, one first


defines vectors xx and yy which give partitions of the sides of the rectangle.
With the function meshgrid one then creates a matrix x, each row of which
equals xx and whose column length is the length of yy, and similarly a matrix
y, each column of which equals yy, as follows:

[x,y] = meshgrid(xx,yy);

One then computes a matrix z, obtained by evaluating f entrywise over


the matrices x and y, to which mesh or surf can be applied. You can, for

41
2 −y 2
example, draw the graph of z = e−x over the square [2,2]*[2,2] as follows
(try it):

xx = -2:.2:2; yy = xx; [x,y] = meshgrid(xx,yy); z = exp(-x.ˆ2 - y.ˆ2);


mesh(z)

One could, of course, replace the first three lines of the preceding with:

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

Try this plot with surf instead of mesh. As noted above, the features of the
axis command described in the section on planar plots also hold for 3-D plots
as do the commands for titles, axes labelling and the command hold.
The color shading of surfaces is set by the shading command. There are
three settings for shading: faceted (default), interpolated, and flat. These
are set by the commands:

shading faceted, shading interp, or shading flat

Note that on surfaces produced by surf, the settings interpolated and flat
remove the superimposed mesh lines. Experiment with various shadings on
the surface produced above. The command shading (as well as colormap
and view below) should be entered after the surf command. The color profile
of a surface is controlled by the colormap command. Available predefined
colormaps include:

hsv (default), hot, cool, jet, pink, copper, flag, gray, bone

The command colormap(cool) will, for example, set a certain color profile
for the current figure. Experiment with various colormaps on the surface
produced above.
The command view can be used to specify in spherical or cartesian coor-
dinates the viewpoint from which the 3-D object is to be viewed. See help
view.
The MATLAB function peaks generates an interesting surface on which
to experiment with shading, colormap, and view. Plots of parametrically
defined surfaces can also be made. The MATLAB functions sphere and
cylinder will generate such plots of the named surfaces. (See edit sphere and

42
type cylinder.)
The following is an example of a similar function which generates a plot
of a torus.
function [x,y,z] = torus(r,n,a)
% TORUS Generate a torus
% torus(r,n,a) generates a plot of a torus with central
% radius a and lateral radius r. n controls the number
% of facets on the surface. These input variables are optional
% with defaults r = 0.5, n = 30, a = 1.
%
% [x,y,z] = torus(r,n,a) generates three (n+1)-by-(n+1)
% matrices so that surf(x,y,z) will produce the torus.
%
% See also SPHERE, CYLINDER
if nargin < 3
a = 1;
end
if nargin < 2
n = 30;
end
if nargin < 1
r = 0.5;
end
theta = pi*(0:2:2*n)/n;
phi = 2*pi*(0:2:n)’/n;
xx = (a + r*cos(phi))*cos(theta);
yy = (a + r*cos(phi))*sin(theta);
zz = r*sin(phi)*ones(size(theta));
if nargout == 0
surf(xx,yy,zz)
ar = (a + r)/sqrt(2);
axis([-ar,ar,-ar,ar,-ar,ar])
else
x = xx; y = yy; z = zz;
end
Other 3-D plotting functions you may wish to explore via help are: meshz,
surfc, surfl, contour, pcolor.

43
17.5 Handle Graphics.
Beyond those described above, MATLAB’s graphics system provides low
level functions which permit one to control virtually all aspects of the graph-
ics environment to produce sophisticated plots. Enter the command set(1)
and gca, set(ans) to see some of the properties of figure 1 which one can
control. This system is called Handle Graphics, for which one is referred to
the MATLAB User’s Guide.

44

Potrebbero piacerti anche