expm 包中的 %^% 运算符无法识别稀疏矩阵
%^% operator from expm package doesn't recognize sparse matrices
我正在使用 expm
包中的 %^%
运算符来计算稀疏矩阵的幂,如下所示:
# Convert to sparse
Qm <- Matrix(Qm, sparse = TRUE)
# Calculate the power
Qmp <- expm::`%^%`( Qm, as.numeric(L)-1 )
class(Qm)
returns Matrix
但我收到以下错误:
Error in expm::`%^%`(Qm, as.numeric(L) - 1) : not a matrix
这是因为 %^%
运算符与 Matrix
对象不兼容还是我做错了什么?
文档明确表示只有 class matrix
被接受为输入。您有两个选择:
Qm <- matrix(c(0,1,1,1), 2)
library(Matrix)
Qm <- Matrix(Qm, sparse = TRUE)
library(expm)
Qm %^% 3
#Error in Qm %^% 3 : not a matrix
#coerce to dense matrix
as.matrix(Qm) %^% 3
# [,1] [,2]
#[1,] 1 2
#[2,] 2 3
#or use loop
Res <- Qm
for (i in seq_len(3-1)) Res <- Res %*% Qm
#2 x 2 sparse Matrix of class "dgCMatrix"
#
#[1,] 1 2
#[2,] 2 3
我正在使用 expm
包中的 %^%
运算符来计算稀疏矩阵的幂,如下所示:
# Convert to sparse
Qm <- Matrix(Qm, sparse = TRUE)
# Calculate the power
Qmp <- expm::`%^%`( Qm, as.numeric(L)-1 )
class(Qm)
returns Matrix
但我收到以下错误:
Error in expm::`%^%`(Qm, as.numeric(L) - 1) : not a matrix
这是因为 %^%
运算符与 Matrix
对象不兼容还是我做错了什么?
文档明确表示只有 class matrix
被接受为输入。您有两个选择:
Qm <- matrix(c(0,1,1,1), 2)
library(Matrix)
Qm <- Matrix(Qm, sparse = TRUE)
library(expm)
Qm %^% 3
#Error in Qm %^% 3 : not a matrix
#coerce to dense matrix
as.matrix(Qm) %^% 3
# [,1] [,2]
#[1,] 1 2
#[2,] 2 3
#or use loop
Res <- Qm
for (i in seq_len(3-1)) Res <- Res %*% Qm
#2 x 2 sparse Matrix of class "dgCMatrix"
#
#[1,] 1 2
#[2,] 2 3