I have a large sparse matrix (dgCMatrix
) in R, and I would like to have the exponential of each element of this matrix. More precisely, I would like to do 1-exp(-x) to each element of the matrix. Unfortunately, when I do this in R, there is a sparse->dense coercion
which takes a lot of time and memory (see example below).
library(Matrix)
i <- sample(20000, 20000); j <- sample(20000, 20000); x <- 7 * (1:20000)
A <- sparseMatrix(i, j, x = x)
1 - exp(-A)
Is there a way to avoid this coercion in R? As 1-exp(0) is 0, maybe sparsity can be preserved.
Probably you can try
A@x <- 1 - exp(-A@x)
such that you update the non-sparse entries only.
For very small A@x
, we can use
A@x <- -expm1(-A@x) # thanks for the comment from jblood94
or just simply
A <- -expm1(-A) # thanks for the comment from Ben Bolker