gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:32:33 25 4
gpt4 key购买 nike

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

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

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

  private var relationMatrix = Array.ofDim[Float](numOfRows,numOfCols)

但是我如何在没有任何大小的情况下定义它,并稍后初始化它?

最佳答案

您是否考虑过使用选项?

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

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

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

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

或在其上绘制 map ,如下所示:

def matrixOperation: Option[Float] = relationMatrix.map { 
matrix: Array[Array[Float]] =>
// Operation logic here, executes only if the matrix is initialized
}

关于arrays - 如何在 Scala 中定义和初始化矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25093483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com