How to compute the power of a matrix in R [duplicate]

给你一囗甜甜゛ 提交于 2020-08-04 03:30:08

问题


I'm trying to compute the -0.5 power of the following matrix:

S <- matrix(c(0.088150041, 0.001017491 , 0.001017491, 0.084634294),nrow=2)

In Matlab, the result is (S^(-0.5)):

S^(-0.5)
ans =
 3.3683   -0.0200
-0.0200    3.4376

回答1:


> library(expm)
> solve(sqrtm(S))
            [,1]        [,2]
[1,]  3.36830328 -0.02004191
[2,] -0.02004191  3.43755429



回答2:


After some time, the following solution came up:

"%^%" <- function(S, power) 
   with(eigen(S), vectors %*% (values^power * t(vectors))) 
S%^%(-0.5)

The result gives the expected answer:

              [,1]        [,2]
  [1,]  3.36830328 -0.02004191
  [2,] -0.02004191  3.43755430



回答3:


The square root of a matrix is not necessarily unique (most real numbers have at least 2 square roots, so it is not just matricies). There are multiple algorithms for generating a square root of a matrix. Others have shown the approach using expm and eigenvalues, but the Cholesky decomposition is another possibility (see the chol function).




回答4:


To extend this answer beyond square roots, the following function exp.mat() generalizes the "Moore–Penrose pseudoinverse" of a matrix and allows for one to calculate the exponentiation of a matrix via a Singular Value Decomposition (SVD) (even works for non square matrices, although I don't know when one would need that).

exp.mat() function:

#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)
}

Example

S <- matrix(c(0.088150041, 0.001017491 , 0.001017491, 0.084634294),nrow=2)
exp.mat(S, -0.5)
#            [,1]        [,2]
#[1,]  3.36830328 -0.02004191
#[2,] -0.02004191  3.43755429

Other examples can be found here.



来源:https://stackoverflow.com/questions/16172731/how-to-compute-the-power-of-a-matrix-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!