Matrices

2020

Creating

matrix: Matrices

matrix(1:9, nrow = 3)
#>      [,1] [,2] [,3]
#> [1,]    1    4    7
#> [2,]    2    5    8
#> [3,]    3    6    9

To fill in row-major order, use the byrow argument:

matrix(1:9, nrow = 3, byrow = TRUE)
#>      [,1] [,2] [,3]
#> [1,]    1    2    3
#> [2,]    4    5    6
#> [3,]    7    8    9

Combine matrices via rbind and cbind1 Combine R Objects by Rows or Columns functions:

A <- matrix(1, nrow = 2, ncol = 2)
B <- matrix(runif(4), nrow = 2)
cbind(A, B)
#>      [,1] [,2]      [,3]      [,4]
#> [1,]    1    1 0.9635684 0.5784499
#> [2,]    1    1 0.7787096 0.7738273
rbind(A, B)
#>           [,1]      [,2]
#> [1,] 1.0000000 1.0000000
#> [2,] 1.0000000 1.0000000
#> [3,] 0.9635684 0.5784499
#> [4,] 0.7787096 0.7738273

Operators

(A <- matrix(1:4, nrow = 2))
#>      [,1] [,2]
#> [1,]    1    3
#> [2,]    2    4
(B <- matrix(1, nrow = 2, ncol = 2))
#>      [,1] [,2]
#> [1,]    1    1
#> [2,]    1    1

Operations are element-wise by default:

A + B
#>      [,1] [,2]
#> [1,]    2    4
#> [2,]    3    5
A * B
#>      [,1] [,2]
#> [1,]    1    3
#> [2,]    2    4
sqrt(A)
#>          [,1]     [,2]
#> [1,] 1.000000 1.732051
#> [2,] 1.414214 2.000000

Matrix multiplication using %*% operator:

A %*% B
#>      [,1] [,2]
#> [1,]    4    4
#> [2,]    6    6

Linear Algebra

Transpose

t: Matrix Transpose

t(A)
#>      [,1] [,2]
#> [1,]    1    2
#> [2,]    3    4

Inverse

solve: Solve a System of Equations

solve(A)
#>      [,1] [,2]
#> [1,]   -2  1.5
#> [2,]    1 -0.5

Solving linear systems

A <- matrix(runif(4), nrow = 2)
x <- c(1, 2)
b <- A %*% x
solve(A, b)
#>      [,1]
#> [1,]    1
#> [2,]    2