CSC121 - R Console Friday March 2nd --------------------------- > # Combining Matrices > X <- matrix(1:6, nrow=2, ncol=3) > X [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 > Y <- matrix(3, nrow=2, ncol=4) > Y [,1] [,2] [,3] [,4] [1,] 3 3 3 3 [2,] 3 3 3 3 > # To combine two matrices with the same numbers of rows, we can use the > # function cbind() > cbind(X, Y) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [1,] 1 3 5 3 3 3 3 [2,] 2 4 6 3 3 3 3 > # This 'binds' the columns together - cbind > # If same number of columns, use rbind > Z <- matrix(7, nrow=4, ncol=3) > rbind(X, Z) [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 [3,] 7 7 7 [4,] 7 7 7 [5,] 7 7 7 [6,] 7 7 7 > rbind(X, c(5,6,7)) [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 [3,] 5 6 7 > # rbind can easily add a row to a matrix > # Vectors can be treated as single columns or rows > > # You can change matrix elements in place: > A <- matrix(0, nrow=3, ncol=3) > A [,1] [,2] [,3] [1,] 0 0 0 [2,] 0 0 0 [3,] 0 0 0 > A[2, 1] <- 5 > A[1, 3] <- 7 > A[3, 3] <- 9 > A [,1] [,2] [,3] [1,] 0 0 7 [2,] 5 0 0 [3,] 0 0 9 > # You can change individual rows or columns > A[,1] <- c(1, 2, 3) > A [,1] [,2] [,3] [1,] 1 0 7 [2,] 2 0 0 [3,] 3 0 9 > A[2,] <- c(1, 2, 3) > A [,1] [,2] [,3] [1,] 1 0 7 [2,] 1 2 3 [3,] 3 0 9 > # When we index a single row or column, we get a vector > A[2,] [1] 1 2 3 > # Can repackage as a matrix, but it will give you back a column > matrix(A[2,]) [,1] [1,] 1 [2,] 2 [3,] 3 > # Instead, can set drop=FALSE to maintain row shape > A[2, , drop=FALSE] [,1] [,2] [,3] [1,] 1 2 3 > B <- matrix(1:9, nrow=3) > B [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 > A[1:2, 2:3] [,1] [,2] [1,] 0 7 [2,] 2 3 > B[1:2, 2:3] [,1] [,2] [1,] 4 7 [2,] 5 8 > # To get any sub-matrix, you need to specify the rows and the columns > # that you want to extract using either a sequence > B[c(1,3), c(1,3)] [,1] [,2] [1,] 1 7 [2,] 3 9 > # ...or any numeric vector > B [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 > source('~/Desktop/matrix_functions.R') > PrintMatrix(B) 1 4 7 2 5 8 3 6 9 > B [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 > B[nrow(B),] [1] 3 6 9 > source('~/Desktop/matrix_functions.R') > ChangeEdgesTo(B) Error in ChangeEdgesTo(B) : argument "n" is missing, with no default > ChangeEdgesTo(B, 1) [,1] [,2] [,3] [1,] 1 1 1 [2,] 1 5 1 [3,] 1 1 1 > source('~/Desktop/matrix_functions.R') > LowerOnes(4) [,1] [,2] [,3] [,4] [1,] 1 0 0 0 [2,] 1 1 0 0 [3,] 1 1 1 0 [4,] 1 1 1 1 > LowerOnes(6) [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 0 0 0 0 [2,] 1 1 0 0 0 0 [3,] 1 1 1 0 0 0 [4,] 1 1 1 1 0 0 [5,] 1 1 1 1 1 0 [6,] 1 1 1 1 1 1 > source('~/Desktop/matrix_functions.R') > XMatrix(3) [,1] [,2] [,3] [1,] 1 0 1 [2,] 0 1 0 [3,] 1 0 1 > XMatrix(7) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [1,] 1 0 0 0 0 0 1 [2,] 0 1 0 0 0 1 0 [3,] 0 0 1 0 1 0 0 [4,] 0 0 0 1 0 0 0 [5,] 0 0 1 0 1 0 0 [6,] 0 1 0 0 0 1 0 [7,] 1 0 0 0 0 0 1