R sparse matrix power -
i'm using matrix package create large (~14000x14000) sparse matrix lot of zeros. know best way calculate power of matrix?
i tried a_pow2 = a%^%2 error: error in %^% 2 : not matrix. here's simple example returns same error:
a = matrix(3,2,2) = matrix(a,sparse=true) apow2 = a%^%2
(edited @roland's comments)
a custom function might able solve issue. per documentation of ?expm::`%^%`
compute k-th power of matrix. whereas x^k computes element wise powers, x %^% k corresponds k - 1 matrix multiplications, x %*% x %*% ... %*% x.
we can write new infix operator perform multiplication k-1 times. not sure how scale, works in smaller examples.
> library(matrix) > library(expm) > = matrix(3,2,2) > b = matrix(a,sparse=true) > > # changed lapply rep list > `%^^%` = function(x, k) reduce(`%*%`, rep(list(x), k)) > # per roland loop approach 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
Comments
Post a Comment