1. Accessing MATLAB
On most systems, after logging in one can enter MATLAB with the system
command matlab and exit MATLAB with the command exit
or quit. On a PC, for example, if properly installed, one may
enter MATLAB with the command:
-
C> matlab
and exit it with the command:
-
>> quit
On systems permitting multiple processes, such as a Unix system, you will
find it convenient, for reasons discussed in section 14, to keep both MATLAB
and your local editor active. If you are working on a workstation which
runs processes in multiple windows, you will want to keep MATLAB active
in one window and your local editor active in another. You should consult
your instructor or your local computer center for details of the local
installation.
2. Entering matrices
MATLAB works with essentially only one kind of object---a rectangular numerical
matrix with possibly complex entries; all variables represent matrices.
In some situations, 1-by-1 matrices are interpreted as scalars and matrices
with only one row or one column are interpreted as vectors.
Matrices can be introduced into MATLAB in several different ways:
-
Entered by an explicit list of elements,
-
Generated by built-in statements and functions,
-
Created in M-files (see sections 12 and 14 below),
-
Loaded from external data files (see User's Guide).
For example, either of the statements
-
A = [1 2 3; 4 5 6; 7 8 9]
and
-
A = [
-
1 2 3
-
4 5 6
-
7 8 9 ]
creates the obvious 3-by-3 matrix and assigns it to a variable A.
Try it. The elements within a row of a matrix may be separated by commas
as well as a blank.
When listing a number in exponential form (e.g. 2.34e-9), blank spaces
must be avoided. Listing entries of a large matrix is best done in an M-file,
where errors can be easily edited away (see sections 12 and 14).
The built-in functions rand, magic, and hilb,
for example, provide an easy way to create matrices with which to experiment.
The command rand(n) will create an n x n matrix with randomly
generated entries distributed uniformly between 0 and 1, while rand(m,n)
will create an m x n one. magic(n) will create an integral
n x n matrix which is a magic square (rows and columns have common
sum); hilb(n) will create the n x n Hilbert matrix, the
king of ill-conditioned matrices (m and n denote, of course,
positive integers). Matrices can also be generated with a for-loop (see
section 6 below).
Individual matrix and vector entries can be referenced with indices
inside parentheses in the usual manner. For example, A(2,3) denotes
the entry in the second row, third column of matrix A and x(3)
denotes the third coordinate of vector x. Try it. A matrix or a
vector will only accept positive integers as indices.
3. Matrix operations, array operations
The following matrix operations are available in MATLAB:
+ |
addition |
- |
subtraction |
* |
multiplication |
^ |
power |
' |
transpose |
\ |
left division |
/ |
right division |
These matrix operations apply, of course, to scalars (1-by-1 matrices)
as well. If the sizes of the matrices are incompatible for the matrix operation,
an error message will result, except in the case of scalar-matrix operations
(for addition, subtraction, and division as well as for multiplication)
in which case each entry of the matrix is operated on by the scalar.
The "matrix division" operations deserve special comment. If A
is an invertible square matrix and b is a compatible column, resp.
row, vector, then
-
x = A \ b is the solution of A * x = b and, resp.,
-
x = b / A is the solution of x * A = b.
In left division, if A is square, then it is factored using Gaussian
elimination and these factors are used to solve A * x = b. If A
is not square, it is factored using Householder orthogonalization with
column pivoting and the factors are used to solve the under- or over-determined
system in the least squares sense. Right division is defined in terms of
left division by b / A = (A' \ b')'.
Array operations. The matrix operations of addition and subtraction
already operate entry-wise but the other matrix operations given above
do not---they are matrix operations. It is important to observe
that these other operations, *, ^, \, and /,
can be made to operate entry-wise by preceding them by a period. For example,
either [1,2,3,4].*[1,2,3,4] or [1,2,3,4].\^2 will yield
[1,4,9,16]. Try it. This is particularly useful when using Matlab
graphics.
4. Statements, expressions, and variables; saving a session
MATLAB is an expression language; the expressions you type are interpreted
and evaluated. MATLAB statements are usually of the form
-
variable = expression, or simply
-
expression
Expressions are usually composed from operators, functions, and variable
names. Evaluation of the expression produces a matrix, which is then displayed
on the screen and assigned to the variable for future use. If the variable
name and = sign are omitted, a variable ans (for answer) is automatically
created to which the result is assigned.
A statement is normally terminated with the carriage return. However,
a statement can be continued to the next line with three or more periods
followed by a carriage return. On the other hand, several statements can
be placed on a single line if separated by commas or semicolons.
If the last character of a statement is a semicolon, the printing is
suppressed, but the assignment is carried out. This is essential in suppressing
unwanted printing of intermediate results.
MATLAB is case-sensitive in the names of commands, functions, and variables.
For example, solveUT is not the same as solveut.
The command who will list the variables currently in the workspace.
A variable can be cleared from the workspace with the command clear
variablename. The command clear alone will clear all
nonpermanent variables.
The permanent variable eps (epsilon) gives the machine precision---about
10^(-16) on most machines. It is useful in determining tolerences for convergence
of iterative processes.
A runaway display or computation can be stopped on most machines without
leaving MATLAB with CTRL-C (CTRL-BREAK on a PC).
Saving a session. When one logs out or exits MATLAB all variables
are lost. However, invoking the command save before exiting causes
all variables to be written to a non-human-readable diskfile named matlab.mat.
When one later reenters MATLAB, the command load will restore
the workspace to its former state.
5. Matrix building functions
Convenient matrix building functions are
eye |
identity matrix |
zeros |
matrix of zeros |
ones |
matrix of ones |
diag |
see below |
triu |
upper triangular part of a matrix |
tril |
lower triangular part of a matrix |
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(A) produces a matrix of zeros
of 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.
6. For, while, if --- and relations
In their basic forms, these MATLAB flow control statements operate like
those in most computer languages.
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
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 suppresses printing of unwanted intermediate
results while the last H displays the final result.
While. The general form of a while loop is
-
while relation
-
statements
-
end
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 2^n>=
a:
-
n = 0;
-
while 2^n < a
-
n = n + 1;
-
end
-
n
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
branching 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.
Relations. The relational operators in MATLAB are
< |
less than |
> |
greater than |
<= |
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
When applied to scalars, a relation is actually the scalar 1 or 0 depending
on whether the relation is true or false. Try 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,
-
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).
The for statement permits any matrix to be used instead of
1:n. See the User's Guide for details of how this feature expands
the power of the for statement.
7. 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 |
8. 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 produce 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.
[continue to next section]
[return to Table of Contents]