As noted above, a matrix is just an array with two subscripts. However it is such an important special case it needs a separate discussion. S-PLUS contains many operators and functions that are available only for matrices. For example t(X) is the matrix transpose function, as noted above. The functions nrow(A) and ncol(A) give the number of rows and columns in the matrix A respectively.
The operator %*% is used for matrix multiplication. An
or
matrix may of course be used as an
vector if in the
context such is appropriate. Conversely vectors which occur in matrix
multiplication expressions are automatically promoted either to row or
column vectors, whichever is multiplicatively coherent, if possible,
(although this is not always unambiguously possible, as we see later).
If, for example, A and B are square matrices of the same size, then
A * B
is the matrix of element by element products and
A %*% B
is the matrix product. If x is a vector, then
x %*% A %*% x
The function crossprod() forms ``crossproducts'', meaning that
crossprod(X, y) is the same as t(X) %*% y
but the operation is more efficient. If the second argument to crossprod() is omitted it is taken to be the same as the first.
Other important matrix functions include solve(A, b) for solving equations, solve(A) for the matrix inverse, svd() for the singular value decomposition, qr() for QR decomposition and eigen() for eigenvalues and eigenvectors of symmetric matrices.
The meaning of diag() depends on its argument. diag(vector) gives a diagonal matrix with elements of the vector as the
diagonal entries. On the other hand diag(matrix) gives the vector of
main diagonal entries of matrix. This is the same convention as that
used for diag() in MATLAB. Also, somewhat confusingly, if
k is a single numeric value then diag(k) is the
identity matrix!
A surprising omission from the suite of matrix facilities is a function for the determinant of a square matrix, however the absolute value of the determinant is easy to calculate for example as the product of the singular values. (See later.)