Search code examples
scalascala-breeze

How to Elementwise Sum a Sequence of DenseVectors in Breeze


I have a sequence of DenseVector[Double] and I would like to sum them elementwise to get a single DenseVector[Double]. Is there an easy built-in way of doing this in the Breeze Scala library?


Solution

  • You can use the reduce function and add all the vectors together, as + is defined as Elementwise Addition for DenseVectors:

    val dv = DenseVector[Double](1,2,3)
    
    List(dv, dv, dv).reduce(_ + _)
    // res0: breeze.linalg.DenseVector[Double] = DenseVector(3.0, 6.0, 9.0)
    
    Seq(dv, dv, dv).reduce(_ + _)
    // res1: breeze.linalg.DenseVector[Double] = DenseVector(3.0, 6.0, 9.0)