4

Let's say I have 2 vectors of the same dimensionality:

scala> val v = DenseVector(3.0, 4.0)
v: breeze.linalg.DenseVector[Double] = DenseVector(3.0, 4.0)

scala> val w = DenseVector(5.0, 6.0)
w: breeze.linalg.DenseVector[Double] = DenseVector(5.0, 6.0)

How can I compute a matrix from it, containing all products (something like a cartesian product in db speak):

scala> val x = DenseMatrix(
     | (v(0) * w(0), v(0) * w(1)),
     | (v(1) * w(0), v(1) * w(1))
     | )
x: breeze.linalg.DenseMatrix[Double] =
15.0  18.0
20.0  24.0

I sense you should be able to do it with broadcasting, but I can't figure out how. Thank you.

botkop
  • 934
  • 1
  • 8
  • 17

1 Answers1

4

This is just the outer product of two vectors:

scala> import breeze.linalg._
import breeze.linalg._

scala> val v = DenseVector(3.0, 4.0)
v: breeze.linalg.DenseVector[Double] = DenseVector(3.0, 4.0)

scala>  val w = DenseVector(5.0, 6.0)
w: breeze.linalg.DenseVector[Double] = DenseVector(5.0, 6.0)

scala> v * w.t
res0: breeze.linalg.DenseMatrix[Double] =
15.0  18.0
20.0  24.0
dlwh
  • 2,257
  • 11
  • 23
  • Seems that this solution is not working when using Vector instead of DenseVector. Any idea why ? – mathk May 19 '17 at 13:53