How to divide a Matrix by another matrix in Scala

479 views Asked by At

I have initialized two matrices (X and Y) in Scala as follows,

 var x = ofDim[Int](a1,b1)
 var y = ofDim[Int](a2,b2)

x,y,a1,a2,b1 and b2 are variables. and now i need to decide X by Y (X/Y). How can achieve that?

3

There are 3 answers

0
Alex Javarotti On BEST ANSWER

There is other approach that use Apache Commons. However, it is important observe that the division operation applies multiplication and inversion operations and, some matrix are inversable and others no: https://en.wikipedia.org/wiki/Invertible_matrix

The following example applies the library Apache Commons (Study.scala):

import org.apache.commons.math3.linear._

object Study {

  def main(args: Array[String]): Unit = {

     val xArray = Array(Array(1.0, 2.0), Array(3.0, 4.0))
     val yArray = Array(Array(1.0, 2.0), Array(3.0, 4.0))

     val x = new Array2DRowRealMatrix(xArray)
     val y = new Array2DRowRealMatrix(yArray)

     val yInverse = new LUDecomposition(y).getSolver().getInverse();
     val w = x.multiply(yInverse)

     for(i <- 0 until w.getRowDimension())
         for(j <- 0 until w.getColumnDimension())
             println(w.getEntry(i, j))

    }
}

Tip: If you intend to use the scala console, you need to specify the classpath ...

 scala -classpath .../commons-math3/3.2/commons-math3-3.2.jar

... in the scala session you load the algorithm ...

  :load .../Study.scala

... and the results come out calling the main function of Study (approximation can be applied) ...

 scala> Study.main(null)                                                

0.99 / 1.11E-16 / 0.0 / 1.02

0
user7312896 On

Try:

import breeze.linalg.{DenseMatrix, inv}

val mx = new DenseMatrix(a1, b1, x.transpose.flatten)
val my = new DenseMatrix(a2, b2, y.transpose.flatten)

mx * inv(my)
0
Alex Javarotti On

The library Beeze, as mecioned in other responses, is necessary. You can install it using SBT or Maven

The Breeze project can be download from GitHub

This is the Maven approach:

<dependency>
    <groupId>org.scalanlp</groupId>
    <artifactId>breeze_2.10</artifactId> <!-- or 2.11 -->
    <version>0.12</version>
</dependency>

The code ...

import breeze.linalg.DenseMatrix

object Division {

    def main(args: Array[String]): Unit = {

        var a1 = 10
        var a2 = 11
        var b1 = 12
        var b2 = 13

       //var x = Array.ofDim[Int](a1,b1)
       //var y = Array.ofDim[Int](a2,b2)

       var x = DenseMatrix(a1,b1)
       var y = DenseMatrix(a2,b2)

       var result = x/y
       print(result)
  }
}