Reputation:
How can i write R code finding a inverse matrix without using inbuilt function? we can use "det" function.
Upvotes: 0
Views: 777
Reputation: 12005
The following function will perform any exponentiation of a matrix. The code was taken from here (link). For an inverse, set the argument EXP=-1
:
#The exp.mat function performs can calculate the pseudoinverse of a matrix (EXP=-1)
#and other exponents of matrices, such as square roots (EXP=0.5) or square root of
#its inverse (EXP=-0.5).
#The function arguments are a matrix (MAT), an exponent (EXP), and a tolerance
#level for non-zero singular values.
exp.mat<-function(MAT, EXP, tol=NULL){
MAT <- as.matrix(MAT)
matdim <- dim(MAT)
if(is.null(tol)){
tol=min(1e-7, .Machine$double.eps*max(matdim)*max(MAT))
}
if(matdim[1]>=matdim[2]){
svd1 <- svd(MAT)
keep <- which(svd1$d > tol)
res <- t(svd1$u[,keep]%*%diag(svd1$d[keep]^EXP, nrow=length(keep))%*%t(svd1$v[,keep]))
}
if(matdim[1]<matdim[2]){
svd1 <- svd(t(MAT))
keep <- which(svd1$d > tol)
res <- svd1$u[,keep]%*%diag(svd1$d[keep]^EXP, nrow=length(keep))%*%t(svd1$v[,keep])
}
return(res)
}
Also, the function solve
will provide the inverse:
a <- matrix(rnorm(16), 4, 4)
exp.mat(a, -1)
# [,1] [,2] [,3] [,4]
#[1,] -0.5900474 -0.3388987 0.1144450 0.38623757
#[2,] -1.0926908 -0.8692702 0.4487108 0.11958685
#[3,] 0.5967371 0.8102801 0.2292397 -0.31654754
#[4,] 0.4634810 0.4562516 -0.7958837 -0.08637801
solve(a)
# [,1] [,2] [,3] [,4]
#[1,] -0.5900474 -0.3388987 0.1144450 0.38623757
#[2,] -1.0926908 -0.8692702 0.4487108 0.11958685
#[3,] 0.5967371 0.8102801 0.2292397 -0.31654754
#[4,] 0.4634810 0.4562516 -0.7958837 -0.08637801
Upvotes: 3