发现R里面居然没有矩阵的N次内积函数,网上抄了一个能用的,学习一下
"%^%" <- function(mat, pow) {
if (!is.matrix(mat)) mat <- as.matrix(mat)
stopifnot(!diff(dim(mat)))
if (pow < 0) {
pow <- -pow
mat <- solve(mat)
}
pow <- round(pow)
switch(pow + 1, return(diag(1, nrow(mat))), return(mat))
get.exponents <- function(pow)
if (pow == 0) NULL else c(k <- 2^floor(log2(pow)), get.exponents(pow - k))
ans <- diag(nrow(mat))
dlog2exp <- rev(-diff(c(log2(get.exponents(pow)), 0)))
for (j in 1:length(dlog2exp)) {
if (dlog2exp[j]) for (i in 1:dlog2exp[j]) mat <- mat %*% mat
ans <- ans %*% mat
}
ans
}
例如
a <- matrix(c(0.9,0.7,0.1,0.3),byrow=TRUE, nrow=2, ncol=2)
a
[,1] [,2]
[1,] 0.9 0.7
[2,] 0.1 0.3
b <- a %^% 2
b
[,1] [,2]
[1,] 0.88 0.84
[2,] 0.12 0.16