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?
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: