B=myinverse(A)
where A is a matrix and B is its inverse and A×B = I. The off-diagonal elements of I should be close to zero, if not zero. Likewise, the diagonal elements should be close to 1, if not 1. Small numerical precision errors are acceptable but the function myinverse should be correct and must use co-factors and determinant of A to compute the inverse.
B <- matrix(c(1,-1,2,0), nrow=2)#2x2 square
C <- matrix(c(1,-1,2,0,3,4,6,7,8), nrow=3)#3x3 square
D <- matrix(c(1,-1,2,0,3,4,6,7,8,5,6,7), nrow=3)#3x3 nonsquare test
#function for determining the inverse of a matrix
myinverse<-function(A){
n<-ncol(A)
if(n==nrow(A)){
#square test
if(det(A)!=0){
#determinant is not 0
cofactors<- matrix(0:0,n,n)
for(i in 1:n){
for(j in 1:n){
detVal<-det(A[-i,-j])
cofactors[i,j]<- detVal*(-1^(i+j))
}
}
#inverse calc cofactor matrix transpose divided by the determinant
return(t(cofactors)/det(A))
}else{
stop('Determinant is 0. Break.')
}
}else{
stop('Non-square matrix. Break.')
}
}
#result
myinverse(C)
## [,1] [,2] [,3]
## [1,] -0.06250 -0.3750 -0.281250
## [2,] -0.34375 -0.0625 0.203125
## [3,] -0.15625 0.0625 0.046875
#sanity test
solve(C)
## [,1] [,2] [,3]
## [1,] 0.06250 -0.3750 0.281250
## [2,] -0.34375 0.0625 0.203125
## [3,] 0.15625 0.0625 -0.046875