如何在 Scala 中将一个矩阵除以另一个矩阵

How to divide a Matrix by another matrix in Scala

我已经在 Scala 中初始化了两个矩阵(X 和 Y),如下所示,

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

x,y,a1,a2,b1 和 b2 是变量。 现在我需要用 Y 来决定 X (X/Y)。如何实现?

尝试:

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)

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

可以从 GitHub

下载 Breeze 项目

这是 Maven 方法:

<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)
  }
}

还有其他使用 Apache Commons 的方法。然而,重要的是观察除法运算应用乘法和求逆运算,并且一些矩阵是可逆的而另一些不是:https://en.wikipedia.org/wiki/Invertible_matrix

以下示例应用库 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