Doing Math in R Part 2
1. Finding the sum and difference of these two matrices.
A = matrix(c(2,0,1,3), ncol=2) and B = matrix(c(5,2,4,-1), ncol=2)
a) Find A + B
First, assign the matrices to a value, then assign a new value to represent the sum of both matrices. Run that value to get the new matrix of A + B.
A <- matrix(c(2,0,1,3), ncol=2)
B <- matrix(c(5,2,4,-1), ncol=2)
AB_sum <- A + B
AB_sum
Result:
[,1] [,2]
[1,] 7 5
[2,] 2 2
b) Find A - B
First, assign the matrices to a value, then assign a new value to represent the difference between the two matrices. Run that value to get the new matrix of A - B.
A <- matrix(c(2,0,1,3), ncol=2)
B <- matrix(c(5,2,4,-1), ncol=2)
AB_dif <- A - B
AB_dif
Result:
[,1] [,2]
[1,] -3 -3
[2,] -2 4
2. Using the diag() function to build a matrix of size 4 with the following values in the diagonal 4,1,2,3.
I assigned the four numbers to a vector C, then, using the diag() function, it automatically creates a matrix with those numbers as the diagonal values.
C <- c(4,1,2,3)
diag(C)
Result:
[,1] [,2] [,3] [,4]
[1,] 4 0 0 0
[2,] 0 1 0 0
[3,] 0 0 2 0
[4,] 0 0 0 3
3. Generate the following matrix:
## [,1] [,2] [,3] [,4] [,5]
## [1,] 3 1 1 1 1
## [2,] 2 3 0 0 0
## [3,] 2 0 3 0 0
## [4,] 2 0 0 3 0
## [5,] 2 0 0 0 3
I created a matrix D using the diag() function to make it 5 x 5 and have all the diagonal values equal to 3. Then, I needed to update the values in row 1, columns 2 through 5, to equal 1 and update the values in column 1, rows 2 through 5, to equal 2. Running D at the end gives me the new updated matrix.
D <- diag(x = 3, nrow = 5, ncol = 5)
D[1, 2:5] <- 1
D[2:5, 1] <- 2
D
Result:
[,1] [,2] [,3] [,4] [,5]
[1,] 3 1 1 1 1
[2,] 2 3 0 0 0
[3,] 2 0 3 0 0
[4,] 2 0 0 3 0
[5,] 2 0 0 0 3
Comments
Post a Comment