Search code examples
scalascala-breeze

Converting matrix to array row by row in Breeze


Trying to convert a DenseMatrix to an array row by row. Method .toArray does it column by column.

-0.04202212765812874   0.001493146410211921   0.06454376876354218
-0.0281160194426775    -0.003562772646546364  0.03207217156887054
-0.02658860757946968   -0.005901590455323458  -0.02247502095997334
-0.04329672083258629   3.376986423972994E-4   -0.07749124616384506
-0.05902788043022156   -6.114873685874045E-4  -0.0953570306301117
-0.07074625790119171   -0.007206509355455637  -0.0750989243388176
-0.07417105883359909   -0.004011879675090313  -0.03285343572497368
-0.06564008444547653   -0.007175311911851168  0.007573474664241076
-0.05417965352535248   -0.007217721547931433  0.02540822699666023
-0.05201821774244308   -0.005401707720011473  0.04020853340625763
-0.03879288583993912   -0.01046885177493095   0.04271911829710007

Should be [-0.04202212765812874, 0.001493146410211921, 0.06454376876354218, -0.0281160194426775, -0.003562772646546364, ....]


Solution

  • You can transpose the matrix and then call toArray method:

    import breeze.linalg._
    val mat = new DenseMatrix[Double](2, 2, Array(1.1, 1.2, 1.3, 1.4))
    //1.1  1.3  
    //1.2  1.4  
    
    mat.t.toArray
    // res0: Array[Double] = Array(1.1, 1.3, 1.2, 1.4)