Search code examples
scalamatrixvectorscala-breeze

Converting vector of vectors to Matrix in scala


What is the most efficient way to convert breeze.linalg.Vector[breeze.linalg.Vector[Double]] to a DenseMatrix?

I tried using asDenseMatrix, toBreezeMatrix, creating a new DenseMatrix etc but it seems like I am missing the most simple and obvious way to do this.


Solution

  • Not real pretty, but this will work and is probably fairly efficient:

    val v: Vector[Vector[Double]] = ???
    val matrix = DenseMatrix(v.valuesIterator.map(_.valuesIterator.toArray).toSeq: _*)
    

    You could make this a bit nicer by defining an implicit LiteralRow for subclasses of Vector like so:

    implicit def vectorLiteralRow[E, V](implicit ev: V <:< Vector[E]) = new LiteralRow[V, E] {
      def foreach[X](row: V, fn: (Int, E) => X): Unit = row.foreachPair(fn)
      def length(row: V) = row.length
    }
    

    Now with this implicit in scope you could use

    val matrix = DenseVector(v.toArray: _*)
    

    It seems pretty natural to construct a matrix from its row vectors, so I'm not sure why the breeze library doesn't define implcit LiteralRows for subclasses of Vector. Maybe someone with more knowledge of the breeze library could comment on this.