Doing mathematics with R: Linear algebra in R
Computing with matrices and vectors
You can easily add matrices in R, subtract them, multiply them (also scalar multiplication) and exponentiate them. Examples illustrate this best. Sometimes you need dedicated R packages.
Computing with matrices and vectors
> A <- matrix(1:6, nrow=2, byrow=TRUE); A
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
> B <- diag(1:3); B
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 2 0
[3,] 0 0 3
> At <- t(A); At # transposed of A
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
> A %*% B # matrix multiplication
[,1] [,2] [,3]
[1,] 1 4 9
[2,] 4 10 18
> A %*% t(A)
[,1] [,2]
[1,] 14 32
[2,] 32 77
> t(A) %*% A
[,1] [,2] [,3]
[1,] 17 22 27
[2,] 22 29 36
[3,] 27 36 45
> .Last.value + B # addition of matrices
[,1] [,2] [,3]
[1,] 18 22 27
[2,] 22 31 36
[3,] 27 36 48
> 3*A # scalar multiplication
[,1] [,2] [,3]
[1,] 3 6 9
[2,] 12 15 18
> v <- 1:3
> A %*% v # matrix-vector multiplication
[,1]
[1,] 14
[2,] 32
> v %*% t(A) # vector-matrix multiplication
[,1] [,2]
[1,] 14 32
> solve(B) # inverse matrix
[,1] [,2] [,3]
[1,] 1 0.0 0.0000000
[2,] 0 0.5 0.0000000
[3,] 0 0.0 0.3333333
> library(pracma); inv(B) # inverse via pracma package
[,1] [,2] [,3]
[1,] 1 0.0 0.0000000
[2,] 0 0.5 0.0000000
[3,] 0 0.0 0.3333333
> library(expm); B %^% 3 # matrix power via expm package
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 8 0
[3,] 0 0 27
If you want to use addition, subtraction, multiplication and exponentiation in components of vector or matrix elements, then use the usual operator. We give some examples.
Operations on matrix elements
> A <- matrix(1:6, nrow=2, byrow=TRUE); A
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
> A^2
[,1] [,2] [,3]
[1,] 1 4 9
[2,] 16 25 36
> A*A
[,1] [,2] [,3]
[1,] 1 4 9
[2,] 16 25 36
> A/A
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 1 1
Unlock full access