Search code examples
listscalamatrixtype-conversionscala-breeze

How to convert a sequence variable into a matrix in Scala


This should be easy, but I'm stuck. I'm trying to convert a Seq[Seq[Double]] type into a Breeze DenseMatrix. (all nested Seq[Double]'s have the same number of elements.)

Converting a single sequence to a DenseVector is pretty easy:

val sss=Seq(2.3,3.4,2.0,1.0)
val bbb=DenseVector(sss:_*)

Is there any similar approach to convert a Seq[Seq[Double]] type to a DenseMatrix? For example:

val sss=Seq(2.3,3.4,2.0,1.0)
val sssM=Seq(sss,sss,sss)
val bbb=DenseVector(sss:_*)
//val bbm= DenseMatrix(sssM:_*:??)  //????

Solution

  • I noticed that the same approach works fine:

    val sss=Seq(2.3,3.4,2.0,1.0)
    val sssM=Seq(sss,sss,sss)
    val bbb=DenseVector(sss:_*)
    val bbm= DenseMatrix(sssM:_*)
    

    Initially I had thought that we need to expand each nested sequence as well. But as stated by Rex Kerr, in a comment below, the Breeze library automatically takes care of that.