seb*_*785 3 r sparse-matrix exponential
我在 R 中有一个大的稀疏矩阵 ( dgCMatrix),我想要这个矩阵的每个元素的指数。更准确地说,我想对矩阵的每个元素执行 1-exp(-x) 。不幸的是,当我在 R 中执行此操作时,需要sparse->dense coercion花费大量时间和内存(请参见下面的示例)。
library(Matrix)
i <- sample(20000, 20000); j <- sample(20000, 20000); x <- 7 * (1:20000)
A <- sparseMatrix(i, j, x = x)
1 - exp(-A)
Run Code Online (Sandbox Code Playgroud)
R 有没有办法避免这种强制?由于 1-exp(0) 为 0,也许可以保留稀疏性。
也许你可以尝试
A@x <- 1 - exp(-A@x)
Run Code Online (Sandbox Code Playgroud)
这样您就可以只更新非稀疏条目。
对于非常小的A@x,我们可以使用
A@x <- -expm1(-A@x) # thanks for the comment from jblood94
Run Code Online (Sandbox Code Playgroud)
或者只是简单地
A <- -expm1(-A) # thanks for the comment from Ben Bolker
Run Code Online (Sandbox Code Playgroud)