Hi,

Say I have a sparse Matrix X, and a sparse vector (stored as a 1-column sparse Matrix A), with X and A having the same number of rows, and I wish to multiply each column of X by A, but would like the operation to take full advantage of the sparseness of both X and A. In other words I want the result to be another sparse Matrix but not having any zeros calculated or stored unnecessarily. For concreteness,

   library(Matrix)
   set.seed(6860)
   X <- sparseMatrix(i = sample(1:10, 5L),
                     j = sample(1:10, 5L),
                     x = rep(1, 5),
                     dims = c(10L, 10L)
                     )
   A <- sparseMatrix(i = sample(1:10, 5L),
                     j = rep(1L, 5L),
                     x = rep(1, 5),
                     dims = c(10L, 1L)
                     )

and observe that

   print(X * A[, 1L, drop=TRUE])

gives the following, in which three 0s are not represented sparsely,

   10 x 10 sparse Matrix of class "dgCMatrix"

    [1,] . . . . . . . . . .
    [2,] . . 1 . . . . . . .
    [3,] . . . . . . . . . .
    [4,] . . . . . 0 . . . .
    [5,] . . . . . . 0 . . .
    [6,] . 1 . . . . . . . .
    [7,] . . . . . . . . . .
    [8,] . . . . . . . . . .
    [9,] . . . . . . . . . .
   [10,] 0 . . . . . . . . .

in other words I am wondering if there is a more efficient way to arrive at the same result as,

   print(X * A[, rep(1L, ncol(X)), drop=FALSE])

   10 x 10 sparse Matrix of class "dgCMatrix"

    [1,] . . . . . . . . . .
    [2,] . . 1 . . . . . . .
    [3,] . . . . . . . . . .
    [4,] . . . . . . . . . .
    [5,] . . . . . . . . . .
    [6,] . 1 . . . . . . . .
    [7,] . . . . . . . . . .
    [8,] . . . . . . . . . .
    [9,] . . . . . . . . . .
   [10,] . . . . . . . . . .

without the additional overhead of duplicating A for ncol(X) times.

This seems like such a simple thing, but has me stumped. Any ideas?

Regards,
Ben

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to