Module # 6 Doing math in R part 2
Module # 6 Doing math in R part 2 1. Matrix Operations Given two matrices: A <- matrix(c(2, 0, 1, 3), ncol = 2) B <- matrix(c(5, 2, 4, -1), ncol = 2) a) Find A + B To find the sum of matrices A and B , simply add corresponding elements: A + B Output: [,1] [,2] [1,] 7 2 [2,] 5 2 Explanation: The sum of the matrices is calculated element by element: (2 + 5) = 7 (0 + 2) = 2 (1 + 4) = 5 (3 + -1) = 2 b) Find A - B To find the difference between matrices A and B , subtract corresponding elements: A - B Output: [,1] [,2] [1,] -3 -2 [2,] -3 4 Explanation: The difference of the matrices is calculated element by element: (2 - 5) = -3 (0 - 2) = -2 (1 - 4) = -3 (3 - -1) = 4 2. Creating a Diagonal Matrix To build a 4x4 matrix with the diagonal values 4, 1, 2, and 3 using the diag() function. diag(c(4, 1, 2, 3), nrow = 4) Output: [,1] [,2] [,3] [,4] [1,] 4 0 0 0 [2,] 0 1 0 0 [3,] 0 0 2 0 [4,] 0 0 0 3 Explana...