How to scale matrix using Double with breeze

I use the math part of the Breeze library and have the following matrix:

val matrix = breeze.linalg.DenseMatrix((1.0,2.0),(3.0,4.0)) 

I want to scale it using a scalar double (and add the result to another matrix) using one of the operators *= and :*= :

 val scale = 2.0 val scaled = matrix * scale 

This works fine (more details in my answer below).

Refresh This code works in isolation. I seem to have a problem elsewhere. Sorry for wasting your bandwidth ...

Update 2 However, the code cannot compile if I specifically assign the Matrix type to the Matrix variable:

 val matrix: Matrix[Double] = breeze.linalg.DenseMatrix((1.0,2.0),(3.0,4.0)) val scaled = matrix * scale // does not compile 

The compiler continues to complain that it โ€œcould not find the implicit value of the op parameterโ€.

Can someone explain this please? Is this a mistake in the breeze or is it intentional? TIA.

+4
source share
1 answer

For those of you struggling with Scala and the Breeze library, I would like to describe in detail some of the functions / operators available for Matrix instances here.

Our starting point is a simple Double matrix ( Matrix , and related operations also support Float and Int ):

 scala> val matrix = breeze.linalg.DenseMatrix((1.0,2.0),(3.0,4.0)) 

You can easily print this using

 scala> println(matrix) 1.0 2.0 3.0 4.0 

Breeze supports statements that leave the left operand intact, and those that modify the left operand - for example. * and *= :

 scala> val scaled1 = matrix * 2.0 // returns new matrix! scala> println(matrix) 1.0 2.0 3.0 4.0 scala> println(scaled1) 2.0 4.0 6.0 8.0 scala> println(matrix == scaled1) false scala> val scaled2 = matrix *= 2.0 // modifies and returns matrix! scala> println(matrix) 2.0 4.0 6.0 8.0 scala> println(scaled2) 2.0 4.0 6.0 8.0 scala> println(matrix == scaled2) // rough equivalent of calling Java equals() true 

The hash codes of both variables indicate that they actually point to the same object (which is true according to javadoc and can be verified by searching for sources):

 scala> println(matrix.##) 12345678 scala> println(scaled2.##) 12345678 

This is further illustrated by:

 scala> val matrix2 = breeze.linalg.DenseMatrix((2.0,4.0),(6.0,8.0)) scala> println(matrix == matrix2) true scala> println(matrix2.##) 34567890 
+2
source

All Articles