# [R] sparse matrix from vector outer product

Martin Maechler maechler at stat.math.ethz.ch
Thu Jan 15 09:07:02 CET 2015

```>>>>> Philipp A <flying-sheep at web.de>
>>>>>     on Wed, 14 Jan 2015 14:02:40 +0000 writes:

> Hi,
> creating a matrix from two vectors a, b by multiplying each combination can
> be done e.g. via

> a %*% t(b)

> or via

> outer(a, b)  # default for third argument is '*'

really the best (most efficient) way would be

tcrossprod(a, b)

> But this yields a normal matrix.
of course.

Please always use small self-contained example code,
here, e.g.,

a <- numeric(17); a[3*(1:5)] <- 10*(5:1)
b <- numeric(12); b[c(2,3,7,11)] <- 1:3

> Is there an efficient way to create sparse matrices (from the Matrix
> package) like that?

> Right now i’m doing

> a.sparse = as(a, 'sparseVector')
> b.sparse = as(t(b), 'sparseMatrix')
> a.sparse %*% b.sparse

> but this strikes me as wasteful.

not really wasteful I think. But there is a nicer and more efficient way :

require(Matrix)
tcrossprod(as(a, "sparseVector"),
as(b, "sparseVector"))

now also gives

17 x 12 sparse Matrix of class "dgCMatrix"

[1,] .  .   . . . .   . . . .  . .
[2,] .  .   . . . .   . . . .  . .
[3,] . 50 100 . . . 150 . . . 50 .
[4,] .  .   . . . .   . . . .  . .
[5,] .  .   . . . .   . . . .  . .
[6,] . 40  80 . . . 120 . . . 40 .
[7,] .  .   . . . .   . . . .  . .
[8,] .  .   . . . .   . . . .  . .
[9,] . 30  60 . . .  90 . . . 30 .
[10,] .  .   . . . .   . . . .  . .
[11,] .  .   . . . .   . . . .  . .
[12,] . 20  40 . . .  60 . . . 20 .
[13,] .  .   . . . .   . . . .  . .
[14,] .  .   . . . .   . . . .  . .
[15,] . 10  20 . . .  30 . . . 10 .
[16,] .  .   . . . .   . . . .  . .
[17,] .  .   . . . .   . . . .  . .
>

```