Matrices
Matrices of double values can be created with an assignment statement of the form
variable <- matrix(value, rows, columns);
This statement assigns to variable a matrix initialized with value of size row by columns.
M
[i,j]
accesses to the (i,j) element of a matrix M
.
M
[i,]
accesses to the ith row of M
.
M
[,j]
accesses to the jth column of M
.
Indexing starts at [1,1]
.
Binary operations +, - ,* , /
work on matrices on an element by element basis. If two matrices are
not the same size, then the smaller matrix values are "recycled".
%*%
is used for matrix multiplication and matrix vector multiplication. Solution of matrix equations
(e.g. matrix "division") is accomplished using the solve(
M
,
B
)
command.
In addition to constructing matrix elements by looping over the indices, one can use cbind(...)
and
rbind(...)
to create a row by "binding" together rows or columns.
Useful matrix commands
t(M) |
Returns the transpose of M. |
dim( matrixVariable ) |
Returns the row and column dimensions of matrixVariable as a vector of integers |
diag(...) |
The diag command can be used to extracts matrix diagonals, as well as create diagonal matrices.. See diag for details. |
%*% |
Matrix - matrix and matrix-vector multiplication. Dimensions are checked prior to evaluation. |
solve( M , B ) |
Returns solution of M-1 B. See the original documentation solve for command variants. |
qr | Computes the qr factorization of a matrix. See qr for details. |
eigen | Computes the eigenvalues and eigenvectors of a matrix. See eigen for details. |
svd | Computes the singular value decomposition of a matrix. See svd for details. |
chol |
Routines for creating and working with upper and lower triangular factors of matrices. See chol, backsolve, lower.tri, for details. |
Samples
# Creating a 5 x 4 matrix initialized to 0.0
m <- matrix(0.0,5,4); m [,1] [,2] [,3] [,4] [1,] 0 0 0 0 [2,] 0 0 0 0 [3,] 0 0 0 0 [4,] 0 0 0 0 [5,] 0 0 0 0
# Checking the dimensions
dim(m) [1] 5 4
# Assigning the [5,3] element the value 2.0
m[5,3] <- 2.0; m [,1] [,2] [,3] [,4] [1,] 0 0 0 0 [2,] 0 0 0 0 [3,] 0 0 0 0 [4,] 0 0 0 0 [5,] 0 0 2 0
# Creating a matrix by binding together vectors created
# with the concatenate command.
M <- rbind(c(0.0,1.0),c(20.0,2.0)) M [,1] [,2] [1,] 0 1 [2,] 20 2
# Setting up a vector for the right hand side of a matrix equation
b <- c(0.0,1.0); b [1] 0 1 # Solving the system of linear equations M x = b solve(M,b); [1] 0.05 0.00
UCLA Mathematics Department | ©2000 |