I have a class which has two dimensional array as a private member - k rows and n columns (the size is not known when defining the Matrix).
I want init the Matrix using a special method: initMatrix, which will set the number of rows and cols in the matrix, and init all the data to 0.
I saw a way to init a multi-dimensional array in the following way:
private var relationMatrix = Array.ofDim[Float](numOfRows,numOfCols)
but how can I define it without any size, and init it later?
Did you consider using an Option?
class MyClass() {
private var relationMatrix: Option[Array[Array[Float]]] = None
def initMatrix(numOfRows:Int, numOfCols:Int): Unit = {
relationMatrix = Some(/* Your initialization code here */)
}
}
The pros of this approach is that in any time you can know whether your matrix is initialized or not, by using relationMatrix.isDefined
, or by doing pattern matching,
def matrixOperation: Float = relationMatrix match {
case Some(matrix) =>
// Matrix is initialized
case None =>
0 // Matrix is not initialized
}
or map on it, like this:
def matrixOperation: Option[Float] = relationMatrix.map {
matrix: Array[Array[Float]] =>
// Operation logic here, executes only if the matrix is initialized
}
For declaring a mutable 2D array of floats without setting dimensions and values, consider
var a: Array[Array[Float]] = _
a: Array[Array[Float]] = null
For initialising it consider the use of Array.tabulate
like this
def init (nRows: Int, nCols: Int) = Array.tabulate(nRows,nCols)( (x,y) => 0f )
Thus for instance,
a = init(2,3)
delivers
Array[Array[Float]] = Array(Array(0.0, 0.0, 0.0), Array(0.0, 0.0, 0.0))
Update the use of Option
(already suggested by @Radian) proves type-safe and more robust at run-time, in contrast with null
initialisation; hence, consider also Option(Array.tabulate)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With