scalascala-breezescalala

How to perform element-wise scalar operations on a vector with Scala Breeze?


With Scalala it was possible to perform element-wise operations on a Vector using a scalar operand. Say you have a Vector of random numbers between 0 and 1 and you want to subtract each value from 1:

import breeze.linalg._

val x = DenseVector.rand(5)
val y = 1d :- x  //DOESN'T COMPILE: "value :- is not a member of Double"

Unlike Scalala, Breeze fails to compile with this approach. You can work around this by generating a Vector of ones but it just seems like there should be a better way.

val y = DenseVector.ones[Double](x.size) :- x

Another workaround would be to use the mapValues method which is a bit more readable:

val y = x mapValues { 1 - _ }

What is the proper way to accomplish this with Breeze?


Solution

  • This is an old question and is sligthly outdated. Currently, with breeze 1.0 and scala 2.11 this syntax is now supported:

    import breeze.linalg._
    
    val x = DenseVector.rand(5)
    val y = 1d :- x 
    

    Output:

    import breeze.linalg._
    x: breeze.linalg.DenseVector[Double] = DenseVector(0.8274425487378012, 0.11585689753323769, 0.9691257294006741, 0.15061939654911782, 0.8337942418593918)
    warning: there was one deprecation warning; re-run with -deprecation for details
    y: breeze.linalg.DenseVector[Double] = DenseVector(0.1725574512621988, 0.8841431024667623, 0.030874270599325904, 0.8493806034508822, 0.16620575814060823)