Problem Set 1

Problem Set 2

write a function B = myinverse(A) to compute the inverse of a well-conditioned full-rank square matrix using co-factors

From section 1, we compute its determinant and all its co-factors. We take the transpose of the co-factor matrix and divide it by the determinant of the matrix to get the inverse. \(A^{-1} = C^T/\det(A)\)

myinverse <- function(A) {
  # Find the dimension and determinant of the matrix; make co-factor matrix
  adim <- dim(A)[1]
  adet <- det(A)
  C <- A
  
  # Go through all the rows
  for (i in 1: adim) {
    
    # Go through all the columns
    for (j in 1: adim) {
       # Find determinate for sub-matrix
       D <- A[-i, -j]
       ddet <- det(D)
       # Make cofactor matrix element
       C[i, j] <- (-1)^(i+j) * ddet
    }
  }
  B <- t(C)
  B <- B / adet
  return(B)
}
mat <- matrix(c(1, 2, 3, 1, 1, 1, 2, 0, 1),nrow=3)
mat
##      [,1] [,2] [,3]
## [1,]    1    1    2
## [2,]    2    1    0
## [3,]    3    1    1
invmat <- myinverse(mat)
invmat
##            [,1]       [,2]       [,3]
## [1,] -0.3333333 -0.3333333  0.6666667
## [2,]  0.6666667  1.6666667 -1.3333333
## [3,]  0.3333333 -0.6666667  0.3333333
invmat %*% mat
##               [,1]          [,2] [,3]
## [1,]  1.000000e+00  0.000000e+00    0
## [2,]  4.440892e-16  1.000000e+00    0
## [3,] -2.220446e-16 -5.551115e-17    1
solve(mat)
##            [,1]       [,2]       [,3]
## [1,] -0.3333333 -0.3333333  0.6666667
## [2,]  0.6666667  1.6666667 -1.3333333
## [3,]  0.3333333 -0.6666667  0.3333333