user9529330
user9529330

Reputation: 89

Speed up sparse matrix multiplication in R

I am trying to multiply a matrix (made up of few 1's and majority O's) with a vector using %*% function in R, this process is taking huge amount of time. Is there a way I can make this faster??

Thanks

Upvotes: 2

Views: 4662

Answers (1)

dmca
dmca

Reputation: 695

You can create a sparse matrix using the Matrix package. Matrix/vector multiplication may be faster in this case. For example:

library(Matrix)
library(tictoc)
set.seed(123)
v <- sample(1e4)
m  <- Matrix(sample(c(0, 1), length(v) ^ 2, T, c(.99, .01)),
         length(v), length(v), sparse = F)
sm <- Matrix(m, sparse = T)
tic("dense")
x <- m %*% v
toc()
#> dense: 0.094 sec elapsed
tic("sparse")
y <- sm %*% v
toc()
#> sparse: 0.006 sec elapsed

Upvotes: 6

Related Questions