Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Breeze DenseMatrix from a List of double arrays in scala

I have a structure List[Array[Double]] and I want to convert to a DenseMatrix. I have this solution but I think there might be a better way:

val data = List[Array[Double]]
val rows = data.length;
val cols = data(0).length;
val matrix = DenseMatrix.zeros[Double](rows, cols)
for (i <- 0 until data.length) {
  for (j <- 0 until data(i).length) {
    matrix(i,j)= data(i)(j)

  }
}

I've been through the Breeze docs but didn't find anything. Is there a better way?

like image 349
MLeiria Avatar asked Dec 13 '25 09:12

MLeiria


1 Answers

You can try this:

val matrix = DenseMatrix(data:_*)

EDIT1

For an explanation of how it works, you can consider data: _* as expansion into variable arguments. For example if

val data = List[Array[Double]](Array(1.0, 1.0), Array(2.0, 2.0))

Then DenseMatrix(data:_*) is same as saying DenseMatrix(Array(1.0, 1.0), Array(2.0, 2.0))

For more details:

  • Syntax sugar: _* for treating Seq as method parameters
  • Creating a Breeze DenseMatrix using an existing List of Lists in Scala
like image 162
tuxdna Avatar answered Dec 15 '25 06:12

tuxdna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!