Module #6
In this module, we did more math with matrices!
We were asked to examine two matrices, add them, minus them, and then use the diag() function. We were also asked to replicate/recreate a matrix with certain criteria.
#Start with two matrices
A = matrix(c(2, 0, 1, 3), ncol = 2)
B = matrix(c(5, 2,4, -1), ncol = 2)
#Call/View matrices
A
[,1] [,2]
[1,] 2 1
[2,] 0 3
B
[,1] [,2]
[1,] 5 4
[2,] 2 -1
#It appears that both matrices are the same size, therefore can be combined, added, subtracted.. etc..
# Find A + B
C <- A + B
#Call / View matrix
C
[,1] [,2]
[1,] 7 5
[2,] 2 2
# Find A - B
D <- A - B
#Call / View matrix
D
[,1] [,2]
[1,] -3 -3
[2,] -2 4
#Use the diag() function to build a matric of size 4 with values 4, 1, 2, 3
E <- c(4, 1, 2, 3)
G <- diag(E)
#Call / View matrix
G
[,1] [,2] [,3] [,4]
[1,] 4 0 0 0
[2,] 0 1 0 0
[3,] 0 0 2 0
[4,] 0 0 0 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
#Makes 3 in diag
H <- diag(x = 3, nrow = 5)
H
[,1] [,2] [,3] [,4] [,5]
[1,] 3 0 0 0 0
[2,] 0 3 0 0 0
[3,] 0 0 3 0 0
[4,] 0 0 0 3 0
[5,] 0 0 0 0 3
#Adds 2 to col 1, rows 2:5
H[2:5] <- c(2)
H
[,1] [,2] [,3] [,4] [,5]
[1,] 3 0 0 0 0
[2,] 2 3 0 0 0
[3,] 2 0 3 0 0
[4,] 2 0 0 3 0
[5,] 2 0 0 0 3
#Adds 1 to row 1, col 2:5
H[1, 2:5] <- c(1)
H
[,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
Please see my Github!
Comments
Post a Comment