如何在 Scala 中定义和初始化矩阵

Ale*_*x L 5 arrays scala matrix

我有一个类,它具有二维数组作为私有成员 - k 行和 n 列(定义矩阵时不知道大小)。

我想使用一种特殊的方法初始化矩阵:initMatrix,它将设置矩阵中的行数和列数,并将所有数据初始化为 0。

我看到了一种通过以下方式初始化多维数组的方法:

  private var relationMatrix = Array.ofDim[Float](numOfRows,numOfCols)
Run Code Online (Sandbox Code Playgroud)

但是我如何定义它没有任何大小,然后再初始化它?

Rad*_*ian 5

你考虑过使用 Option 吗?

class MyClass() {
  private var relationMatrix: Option[Array[Array[Float]]] = None

  def initMatrix(numOfRows:Int, numOfCols:Int): Unit = {
    relationMatrix = Some(/* Your initialization code here */)
  }
}
Run Code Online (Sandbox Code Playgroud)

这种方法的优点是,您可以通过使用relationMatrix.isDefined或进行模式匹配,随时知道您的矩阵是否已初始化,

def matrixOperation: Float = relationMatrix match { 
  case Some(matrix) =>
    // Matrix is initialized
  case None =>
    0 // Matrix is not initialized
}
Run Code Online (Sandbox Code Playgroud)

或在其上映射,如下所示:

def matrixOperation: Option[Float] = relationMatrix.map { 
  matrix: Array[Array[Float]] =>
  // Operation logic here, executes only if the matrix is initialized 
}
Run Code Online (Sandbox Code Playgroud)