# Chapter 4 Matrices

We use the matrix function to create a matrix from a vector of values.

A <- matrix(c(1,2,4,8), nrow=2, ncol=2, byrow=FALSE)
A
##      [,1] [,2]
## [1,]    1    4
## [2,]    2    8
B <- matrix(c(1,2,4,8), nrow=2, ncol=2, byrow=TRUE)
B
##      [,1] [,2]
## [1,]    1    2
## [2,]    4    8

We can extract elements of the matrix with square brackets. Look up the documentation with ?"[". We can extract elements by row

A[1,]
## [1] 1 4
A[2,]
## [1] 2 8

by column

A[,1]
## [1] 1 2
A[,2]
## [1] 4 8

or by element

A[1,2]
## [1] 4
A[2,1]
## [1] 2

We can also use square brackets to replace columns, rows, or elements of a matrix.

A[1,] <- c(1, 2)
A
##      [,1] [,2]
## [1,]    1    2
## [2,]    2    8
A[,2] <- c(2, 1)
A
##      [,1] [,2]
## [1,]    1    2
## [2,]    2    1
A[2,1] <- -1
A
##      [,1] [,2]
## [1,]    1    2
## [2,]   -1    1

The arithmetic operators perform elementwise operations for matrices, as with vectors.

A + B
##      [,1] [,2]
## [1,]    2    4
## [2,]    3    9
A - B
##      [,1] [,2]
## [1,]    0    0
## [2,]   -5   -7
A * B
##      [,1] [,2]
## [1,]    1    4
## [2,]   -4    8
A / B
##       [,1]  [,2]
## [1,]  1.00 1.000
## [2,] -0.25 0.125
A ^ B
##      [,1] [,2]
## [1,]    1    4
## [2,]    1    1

To perform matrix multiplication, we use the %*% operator.

A %*% B
##      [,1] [,2]
## [1,]    9   18
## [2,]    3    6

To find the inverse of a matrix, we use the solve function.

solve(A)
##           [,1]       [,2]
## [1,] 0.3333333 -0.6666667
## [2,] 0.3333333  0.3333333

We also use the solve function to solve the equation $$Ax = b$$.

solve(A, b=c(3,9))
## [1] -5  4

To find the determinant of a matrix, we use the det function.

det(A)
## [1] 3

We can write functions to extract a general matrix diagonal

gen.diag <- function(A, k) A[row(A) == col(A) - k]

and to replace a general matrix diagonal

gen.diag<- <- function(A, k, value) {
A[row(A) == col(A) - k] <- value
A
}

Letâ€™s test these functions for extracting and replacing a general matrix diagonal.

C <- matrix(c(1,0,-1,8,1,0,-1,9,-2), nrow=3, byrow=TRUE)
C
##      [,1] [,2] [,3]
## [1,]    1    0   -1
## [2,]    8    1    0
## [3,]   -1    9   -2
gen.diag(C, -1)
## [1] 8 9
gen.diag(C, -1) <- c(2,1)
C
##      [,1] [,2] [,3]
## [1,]    1    0   -1
## [2,]    2    1    0
## [3,]   -1    1   -2

We can combine matrices and vectors with by columns with cbind and by rows with rbind.

B
##      [,1] [,2]
## [1,]    1    2
## [2,]    4    8
cbind(B, c(16, 32))
##      [,1] [,2] [,3]
## [1,]    1    2   16
## [2,]    4    8   32
rbind(B, c(16, 32))
##      [,1] [,2]
## [1,]    1    2
## [2,]    4    8
## [3,]   16   32