how DenseVector to convert to DenseMatrix

227 Views Asked by At

I have data for N rows xM rows DenseVector[DenseVector[Double]] (or DenseMatrix[DenseMatrix[Double]]) and want to convert this object into an NxM's DenseMatrix object

DenseVector(DenseVector(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0), DenseVector(11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0), DenseVector(11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0), DenseVector(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0))

converted single DenseMatrix object

 1.0,  2.0,  3.0,  4.0,  5.0,  6.0,  7.0,  8.0
11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0
11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0
 1.0,  2.0,  3.0,  4.0,  5.0,  6.0,  7.0,  8.0

Here is the test code, It can't executed.

object BreezeTest extends App {
    val mx = Array(Array(Array(1.0,2.0,3.0,4.0),Array(5.0,6.0,7.0,8.0)),Array(Array(11.0,12.0,13.0,14.0),Array(15.0,16.0,17.0,18.0)))

    val my = Array(Array(0,1),Array(1,0))
    val myND =DenseMatrix(my:_*)
    val newND = myND.map(s=>DenseVector(mx(s).flatten)).flatten()   // here is 4d array,It's difficult process,so try flat to 2d matrix 
    println(newND)
    println(DenseMatrix.vertcat(newND:_*)

}
1

There are 1 best solutions below

0
On
val mx = DenseVector(DenseVector(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0), 
                     DenseVector(11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0), 
                     DenseVector(11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0), 
                     DenseVector(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0))
   
val m = 4
val n = 8
new DenseMatrix(4, 8, mx(1 until mx.size).foldLeft(mx(0)){ case (acc, v) => 
    DenseVector.vertcat(acc, v)
}.toArray)