Scala + Breeze - How to operate on indexed elements?

561 Views Asked by At

I would like to perform an element-wise operation like:

matrixOne(indices) :*= matrixTwo(indices)

i.e.

matrixOne(indices) = matrixOne(indices) :* matrixTwo(indices)

Although I don't believe that syntax works, and I don't see an easy way of doing this. Is there a simple way that doesn't involve a loop over the elements?

Thanks!

1

There are 1 best solutions below

0
On BEST ANSWER

But it does work!

scala> val dm, dm2 = DenseMatrix.rand(3,3)
dm: breeze.linalg.DenseMatrix[Double] =
0.28936576129658276  0.666815685335741   0.281387720258117
0.5738723072553482   0.7833150021047757  0.35576679755808027
0.9108889661007076   0.1477391442357301  0.15849984459500677
dm2: breeze.linalg.DenseMatrix[Double] =
0.431188741169817    0.5744275775115384  0.12976923536278662
0.08719379330185784  0.5968447834511466  0.15023676086236382
0.9136600875085321   0.9976862794513606  0.8561688429270904

scala> dm(IndexedSeq(0 -> 1, 1 -> 2)) += dm2(IndexedSeq(2 -> 1, 0 -> 0))
res4: breeze.linalg.Vector[Double] = breeze.linalg.SliceVector@3e6c9b94

scala> dm
res5: breeze.linalg.DenseMatrix[Double] =
0.28936576129658276  1.6645019647871016  0.281387720258117
0.5738723072553482   0.7833150021047757  0.7869555387278973
0.9108889661007076   0.1477391442357301  0.15849984459500677

scala> dm(IndexedSeq(0 -> 1, 1 -> 2)) :*= dm2(IndexedSeq(2 -> 1, 0 -> 0))
res6: breeze.linalg.Vector[Double] = breeze.linalg.SliceVector@6115d457

scala> dm
res7: breeze.linalg.DenseMatrix[Double] =
0.28936576129658276  1.660650772387923   0.281387720258117
0.5738723072553482   0.7833150021047757  0.33932636810069716
0.9108889661007076   0.1477391442357301  0.15849984459500677