简体   繁体   English

R稀疏矩阵幂

[英]R sparse matrix power

I'm using the Matrix package to create a large (~14000x14000) sparse matrix with a lot of zeros. 我正在使用Matrix程序包创建带有很多零的大型(〜14000x14000)稀疏矩阵。 Does anyone know the best way to calculate the power of this matrix? 有谁知道计算此矩阵幂的最佳方法?

I tried A_pow2 = A%^%2 but I get the error: Error in A %^% 2 : not a matrix. 我尝试了A_pow2 = A%^%2,但出现错误:A%^%2中的错误:不是矩阵。 Here's a simple example that returns the same error: 这是一个返回相同错误的简单示例:

A = matrix(3,2,2)
A = Matrix(A,sparse=TRUE)
Apow2 = A%^%2

(edited thanks to @Roland's comments) (由于@Roland的评论而编辑)

A custom function might be able to solve your issue. 自定义功能可能能够解决您的问题。 Per documentation of ?expm::`%^%` 根据?expm::`%^%`文档

Compute the k-th power of a matrix. 计算矩阵的第k次幂。 Whereas x^k computes element wise powers, x %^% k corresponds to k - 1 matrix multiplications, x %*% x %*% ... %*% x. 而x ^ k计算元素的方次幂,x%^%k对应于k-1矩阵乘法,x%*%x%*%...%*%x。

We can write a new infix operator to perform the multiplication k-1 times. 我们可以编写一个新的中缀运算符来执行k-1次乘法。 Not sure how well it will scale, but it works in smaller examples. 不确定它将扩展的程度如何,但是可以在较小的示例中使用。

> library(Matrix)
> library(expm)
> A = matrix(3,2,2)
> B = Matrix(A,sparse=TRUE)
> 
> # changed lapply to rep list
> `%^^%` = function(x, k) Reduce(`%*%`, rep(list(x), k))
> # per Roland for loop approach will be better on memory
> `%^^%` = function(x, k) {for (i in 1:(k - 1)) x <- x %*% x; x}
> 
> as.matrix(B%^^%2)
     [,1] [,2]
[1,]   18   18
[2,]   18   18
> A%^%2
     [,1] [,2]
[1,]   18   18
[2,]   18   18

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM