Search code examples
scalamatrixscala-breeze

Add a vector to every column of a matrix, using Scala Breeze


I have a matrix M of (L x N) rank and I want to add the same vector v of length L to every column of the matrix. Is there a way do this please, using Scala Breeze?

I tried:

val H = DenseMatrix.zeros(L,N)
  for (j <- 0 to L) {
  H (::,j) = M(::,j) + v
}

but this doesn't really fit Scala's immutability as H is then already defined and therefore gives a reassignment to val error. Any suggestions appreciated!


Solution

  • To add a vector to all columns of a matrix, you don't need to loop through columns; you can use the column broadcasting feature, for your example:

    H(::,*) + v             // assume v is breeze dense vector
    

    Should work.


    import breeze.linalg._
    
    val L = 3
    val N = 2
    val v = DenseVector(1.0,2.0,3.0)
    val H = DenseMatrix.zeros[Double](L, N)
    
    val result = H(::,*) + v
    
    //result: breeze.linalg.DenseMatrix[Double] = 1.0  1.0  
    //                                            2.0  2.0  
    //                                            3.0  3.0