HW2.pdf - HW2 hw2 Question 1 1a example < matrix(1:25 ncol = 5 i < ncol(example mat_vec < matrix(c(1:i ncol = 1 byrow = TRUE mat_index < cbind(mat_vec

# HW2.pdf - HW2 hw2 Question 1 1a example < matrix(1:25 ncol...

• Homework Help
• 8

This preview shows page 1 - 5 out of 8 pages.

HW2 hw2 Question 1 1a) example <- matrix ( 1 : 25 , ncol = 5 ) i <- ncol (example) mat_vec <- matrix ( c ( 1 : i), ncol = 1 , byrow = TRUE ) mat_index <- cbind (mat_vec, mat_vec) mat_index ## [,1] [,2] ## [1,] 1 1 ## [2,] 2 2 ## [3,] 3 3 ## [4,] 4 4 ## [5,] 5 5 example[mat_index] ## [1] 1 7 13 19 25 1b) mat_vec2 <- matrix ( c ( 2 : i), ncol = 1 , byrow = TRUE ) mat_vec3 <- matrix ( c ( 1 : (i -1 )), ncol = 1 , byrow = TRUE ) mat_index2 <- cbind (mat_vec2, mat_vec3) mat_index2 ## [,1] [,2] ## [1,] 2 1 ## [2,] 3 2 ## [3,] 4 3 ## [4,] 5 4 example[mat_index2] ## [1] 2 8 14 20 1
Question 2 2a) mat <- matrix ( 0 , 3 , 4 ) vec <- rep ( 1 : 3 , 4 ) mat + vec ## [,1] [,2] [,3] [,4] ## [1,] 1 1 1 1 ## [2,] 2 2 2 2 ## [3,] 3 3 3 3 /* for each value in the matrix, the result is the value plus the vector value In this case, the vector adds to each value in the matrix by row. */ 2b) mat <- matrix ( 0 , 3 , 4 ) vec <- 1 : 3 mat + vec ## [,1] [,2] [,3] [,4] ## [1,] 1 1 1 1 ## [2,] 2 2 2 2 ## [3,] 3 3 3 3 /* in this case, matrix has longer length than the vector. However, because the length of the matrix is a multiple of the length of the vector, the vector can be recycled to add on each value in the matrix, until addition is performed to all the values in the matrix . */ 2c) mat <- matrix ( 0 , 3 , 4 ) vec<- 1 : 4 t ( t (mat) + vec) ## [,1] [,2] [,3] [,4] ## [1,] 1 2 3 4 ## [2,] 1 2 3 4 ## [3,] 1 2 3 4 Question 3 vec <- 2 : 6 matrix <- rbind ( 2 : 6 , vec + 1 , vec + 2 , vec + 3 , vec + 4 ) 2
Question 4 4a) ## generic code for permuting columns # m[ ,c(i,j)] <- m[ , c(j,i)] ## testing m <- diag ( 4 ) i = 2 j = 4 m[ , c (i,j)] <- m[ , c (j,i)] m ## [,1] [,2] [,3] [,4] ## [1,] 1 0 0 0 ## [2,] 0 0 0 1 ## [3,] 0 0 1 0 ## [4,] 0 1 0 0 4b) J <- m A <- matrix ( 2 , 4 , 4 ) B <- A * J B ## [,1] [,2] [,3] [,4] ## [1,] 2 0 0 0 ## [2,] 0 0 0 2 ## [3,] 0 0 2 0 ## [4,] 0 2 0 0 D <- J * A D ## [,1] [,2] [,3] [,4] ## [1,] 2 0 0 0 ## [2,] 0 0 0 2 ## [3,] 0 0 2 0 ## [4,] 0 2 0 0 # results are the same Question 5 mu <- c ( 10 , 5 ) Sigma = matrix ( c ( 1 , -0.8 , -0.8 , 1 ), ncol = 2 ) N = 100000 # let s draw 10,000 bivariate normals 3
X = t ( chol (Sigma)) %*% matrix ( rnorm (N * 2 ), nrow= 2 ) + mu plot