MSDS Spring 2018

DATA 605 Fundamentals of Computational Mathematics

Jiadi Li

HW #4 - Problem Set 2: Compute Inverse with Co-factors

1.create a function to compute inverse of a matrix using co-factors.

myinverse <- function(matrixA){
  cofactor_matrix <- matrix(,nrow(matrixA),ncol(matrixA))
  i <- 1
  j <- 1
  while (i <= nrow(matrixA)) {
    while (j <= ncol(matrixA)) {
      factor_ij <- (-1)^(i+j)
      submatrix <- matrixA[-i,-j]
      cofactor_matrix[i,j] <- factor_ij*det(submatrix)
      j <- j+1
    }
    j <- 1
    i <- i+1
    }
  inverseA <- t(cofactor_matrix)/det(matrixA)
  return(inverseA)
}

The function is based on \(A^{-1}=C^{T}/det(A)\) where \(C^{T}\) is the transpose of the co-factor matrix.

2.Examine the function.(assume the matrix is a well-conditioned full-rank square matrix)

testA <- matrix(c(1,3,3,4,6,6,7,7,9,5,3,1,8,3,1,4),byrow = TRUE,4,4)
inverse_A <- myinverse(testA)
testA
##      [,1] [,2] [,3] [,4]
## [1,]    1    3    3    4
## [2,]    6    6    7    7
## [3,]    9    5    3    1
## [4,]    8    3    1    4
inverse_A
##             [,1]         [,2]        [,3]        [,4]
## [1,] -0.32015810  0.134387352 -0.02371542  0.09090909
## [2,]  0.92885375 -0.525691700  0.32806324 -0.09090909
## [3,] -0.62055336  0.470355731 -0.08300395 -0.18181818
## [4,]  0.09881423  0.007905138 -0.17786561  0.18181818
round(testA%*%inverse_A,7)==diag(nrow(testA))
##      [,1] [,2] [,3] [,4]
## [1,] TRUE TRUE TRUE TRUE
## [2,] TRUE TRUE TRUE TRUE
## [3,] TRUE TRUE TRUE TRUE
## [4,] TRUE TRUE TRUE TRUE