Search code examples
scalascala-breeze

How to insert vector of ones to Matrix?


I've a vector and a matrix:

1
1

0 0
0 0

I want to prepend the vector to matrix to produce :

1 0 0
1 0 0

I have so far :

val dv = DenseVector(1.0,1.0);
val dm = DenseMatrix.zeros[Double](2,2)

Reading the API : http://www.scalanlp.org/api/breeze/#breeze.linalg.DenseMatrix and both these docs : https://github.com/scalanlp/breeze/wiki/Quickstart https://github.com/scalanlp/breeze/wiki/Linear-Algebra-Cheat-Sheet

But this operation does not appear to be available ?

Is there a method/function to prepend a vector of ones to a Matrix ?


Solution

  • Another option here. Firstly convert the DenseVector to a 2X1 matrix and then use the DenseMatrix.horzcat() method:

    val newMat = DenseMatrix.horzcat(new DenseMatrix(2,1,dv.toArray), dm)
    
    # breeze.linalg.DenseMatrix[Double] = 1.0  0.0  0.0  
    #                                     1.0  0.0  0.0
    
    newMat.rows
    # 2
    newMat.cols
    # 3