R语言 把一个矩阵提升到一个分数幂
在R编程语言中,矩阵可以被提升到整数和非整数幂。矩阵的幂的计算涉及到矩阵的同时乘以指定幂的整数倍。然而,在小数幂的情况下,我们需要使用内置的R函数来模拟这一操作。
方法1:使用R中的expm包
expm包可以用来进行各种类型的矩阵计算,如对数、指数和其他。这个函数可以计算一个正方形矩阵的指数,这个矩阵是不可对角的。expm包分别包括logm和sqrtm方法。然而,它不能用于处理负分数幂。expm包可以通过以下命令安装在R目录下。
install.packages("expm)
该包被包含在脚本中,然后可以使用expm方法,其语法如下。
expm(x), where x is the matrix
代码
require(expm)
library("expm")
mat <- matrix(c(1, 1, 1, 1), 2, 2)
print ("Original Matrix")
print (mat)
modified_matrix <- 1.1*logm(mat)
# computing power matrix
powmat <- expm(modified_matrix)
# printing the power matrix
print ("Power Matrix")
print (powmat)
输出
[1] "Original Matrix"
[,1] [,2]
[1,] 1 1
[2,] 1 1
[1] "Power Matrix"
[,1] [,2]
[1,] 1.071773 1.071773
[2,] 1.071773 1.071773
方法2:使用R中的powerplus包
使用R中的powerplus包可以将矩阵提升到负的或正的非整数幂。可以使用的矩阵是方形矩阵或具有正特征值的可对角的矩阵。powerplus软件包可以通过以下命令安装到R目录中。
install.packages("powerplus")
然后可以在脚本中包含该包,然后可以使用Matpow()方法,该方法可以用来对一个方形矩阵进行指数幂计算。
语法: Matpow(M, power_number)
参数 :
- M – 一个可诊断的方形矩阵
- power_number – 矩阵的非积分功率因子
返回: 一个提高到power_number系数的矩阵。
例1:下面的例子说明了R语言中的Matpow()方法
# requiring the necessary package
require("powerplus")
# declaring a non diagonalizable matrix
mat <- matrix(c(2, 0, 1, 1), ncol = 2)
print ("Original Matrix")
print (mat)
# raising the matrix to a fractional
# power 0.5
print ("Power Matrix")
Matpow(mat, 0.5)
[1] "Original Matrix"
[,1] [,2]
[1,] 1 1
[2,] 0 1
[1] "Power Matrix"
[,1] [,2]
[1,] 1 0.5
[2,] 0 1.0
例2: 负的积分幂.
Matpow()方法也可以用来解决负积分的问题。如果结果是奇数,则输出为负矩阵,否则为偶数。
# requiring the necessary package
require("powerplus")
# declaring a non diagonalizable matrix
mat <- matrix(c(2, 0, 1, 1), ncol = 2)
print ("Original Matrix")
print (mat)
# raising the matrix to a fractional power 0.5
print ("Power Matrix")
Matpow(mat, -2.1)
输出
[1] "Original Matrix"
[,1] [,2]
[1,] 2 1
[2,] 0 1
[1] "Power Matrix"
[,1] [,2]
[1,] 0.2332582 -0.7667418
[2,] 0.0000000 1.0000000