1.12 Matrix operators

You can add, subtract, multiply, and divide matrices elementwise just like vectors. However, if you have taken linear algebra you know that sometimes you want to use matrix multiplication and inverses rather than elementwise multiplication and division. These are matrix operators.

Some commonly used matrix functions and operators are:

  • View the dimensions (rows, columns) of a matrix: dim()
  • View the number of rows or columns of a matrix: nrow(), ncol()
  • Matrix multiplication: X %*% Y
  • Transpose: t(X)
  • Inverse of a square matrix: solve(X)
  • Extract the diagonal elements of a matrix: diag(X)

NOTE: It is common to use upper case for matrices (X, Y, Z) and lower case for vectors (x, y, z).

For example, consider the following two matrices, where X is 2 \(\times\) 3 and Y is 3 \(\times\) 2.

X <- matrix(c(0, 2, 4, 6, 8, 1), nrow = 3)
Y <- matrix(c(1, 5, 3, 8, 2, 7), nrow = 2)
X
##      [,1] [,2]
## [1,]    0    6
## [2,]    2    8
## [3,]    4    1
Y
##      [,1] [,2] [,3]
## [1,]    1    3    2
## [2,]    5    8    7
dim(X)
## [1] 3 2
dim(Y)
## [1] 2 3
ncol(X)
## [1] 2
nrow(X)
## [1] 3
X %*% Y  # The number of columns of X must match the number of rows of Y
##      [,1] [,2] [,3]
## [1,]   30   48   42
## [2,]   42   70   60
## [3,]    9   20   15
t(X)
##      [,1] [,2] [,3]
## [1,]    0    2    4
## [2,]    6    8    1

The inverse function solve() only works for a square matrix.

X <- matrix(c(3, 2, 4, 6), nrow = 2)
X
##      [,1] [,2]
## [1,]    3    4
## [2,]    2    6
dim(X)
## [1] 2 2
diag(X)
## [1] 3 6
solve(X)
##      [,1] [,2]
## [1,]  0.6 -0.4
## [2,] -0.2  0.3
X %*% solve(X)
##      [,1] [,2]
## [1,]    1    0
## [2,]    0    1