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.
## [,1] [,2]
## [1,] 0 6
## [2,] 2 8
## [3,] 4 1
## [,1] [,2] [,3]
## [1,] 1 3 2
## [2,] 5 8 7
## [1] 3 2
## [1] 2 3
## [1] 2
## [1] 3
## [,1] [,2] [,3]
## [1,] 30 48 42
## [2,] 42 70 60
## [3,] 9 20 15
## [,1] [,2] [,3]
## [1,] 0 2 4
## [2,] 6 8 1
The inverse function solve()
only works for a square matrix.
## [,1] [,2]
## [1,] 3 4
## [2,] 2 6
## [1] 2 2
## [1] 3 6
## [,1] [,2]
## [1,] 0.6 -0.4
## [2,] -0.2 0.3
## [,1] [,2]
## [1,] 1 0
## [2,] 0 1