We have already seen the matrix operator ' (prime) for transposing matrices. The arithmetic operators presented in Section 5 also operate on matrices. In each case the operator behaves in a manner consistent with standard linear algebra practises.
The operators + and - permit the addition and subtraction of matrices,
and are defined whenever the matrices have the same dimension.
For example, the following is a valid expression.
>> [1 2 3; 4 5 6] + [3 2 1; 1 1 1];
The exception to this rule is the addition (subtraction) of a scalar to
(from) a matrix. In this
case the scalar is added to or subtracted from each
element of the matrix individually.
>> [1 2 3] + 1
ans =
2 3 4
The multiplication of two matrices, denoted by A*B, is defined whenever
the inner dimensions of the operands A and B are equal. For example,
if
C=[1 2 3; 4 5 6], D=[1 1 1; 2 2 2], x=[1 1 1]'
then C*x, x'*x (an inner product), x*x' (an outer product)
and C*D' are defined, but C*D is not.
(Give these examples a try and be sure you understand how MATLAB interprets
them.) In the special case when one of the operands is a
scalar, each element of the matrix is multiplied by the scalar.
It is now time to explain the reason for MATLAB's
two division operators. If A
is a square nonsingular matrix then A\B
and B/A formally correspond
to the left and right multiplication of B by A
. (Note: MATLAB
does not actually compute the inverse of A when evaluating these
expressions.) These expressions are used to solve the following types of
systems of equations.
\B solves A*X = B
/B solves X*A = B
\b
(the solution to Ax = b) by factoring A with Gaussian elimination
and then solving two triangular systems to compute x.
When A is not square, MATLAB factors A using Householder
orthogonalization
and the factors are used to solve the under-determined or over-determined
system of equations in the least squares sense. This can lead to surprising
results if the wrong slash is used or if the dimensions of your matrices
are wrong.
Finally, the expression A^p raises A to the p
power. This operation is only defined if A is square and p
is an scalar. For example, A^2 is equivalent to A*A,
although MATLAB does not always compute powers with simple matrix
multiplication.