#
# CHAPTER 5: Matrices
#
# a matrix is a rectangular arrangement of numbers
# the first subscript gives the row number
# the second subscript gives the column number
# matrices are stored column-wise by default
#
# matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE)
#
matrix(1:6, nrow = 2, ncol = 3) # a 2 x 3 matrix
matrix(1:6, 2, 3, byrow = TRUE) # a 2 x 3 matrix
matrix(0, 2, 3) # a 2 x 3 matrix of zeros
matrix(seq(1, 7, 2), 3, 2) # a 3 by 2 matrix with recycling
#
# pasting vectors together to form matrices
#
rbind(1:5, 2:6, 3:7) # row-bind pastes vectors as rows
rbind(1:8, 1:2) # shorter vector gets recycled
x = 1:2 # first column
y = 8:9 # second column
z = cbind(x, y) # column-bind pastes vectors as columns
z # display z
#
# indexing: row then column
#
x = matrix(1:6, 2, 3, byrow = TRUE) # x is a 2 x 3 matrix
x # display x
x[2, 1] # second row, first column of x
x[ , 1] # first column of x
x[2, ] # second row of x
x[2, 2:3] # 2nd row, 2nd and 3rd columns of x
x[1:2, 2:3] # 1st and 2nd row, 2nd and 3rd columns
x[ , -1] # eliminate the first column
x[3] # third element of x (column-major)
#
# arithmetic on matrices
#
x # display x
x + 7 # add 7 to every element of x
7 * x # multiply every element of x by 7
x ^ 2 # square every element of x
x %% 2 # every element of x modulo 2
#
# set first column of x to zero
#
x # display x
x[ , 1] = 0 # zero out the first column
x # display x
#
# now set second row of x to -1
#
x[2, ] = -1 # second row set to -1
x # display x
#
# set x[1, 2] and x[2, 1] to 17
#
x[1, 2] = 17 # set upper left
x[2, 1] = 17 # set lower right
x # display x
#
# set x[1, 2] and x[2, 1] to 19 efficiently
#
index = matrix(c(1:2, 2:1), 2, 2) # define a matrix of subscripts
index # the rows contain target subscripts
x[index] # display targeted values in x
x[index] = 19 # set target values to 19
x # display x