Alex L
Alex L

Reputation: 1089

How to define & init Matrix in Scala

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?

Upvotes: 6

Views: 16920

Answers (4)

elm
elm

Reputation: 20415

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

Upvotes: 2

tabdulradi
tabdulradi

Reputation: 7596

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 
}

Upvotes: 7

Ashalynd
Ashalynd

Reputation: 12573

You can make your initMatrix method part of the companion object.

class Matrix(numOfRows:Int, numOfCols:Int) {
    private var relationMatrix = Array.ofDim[Float](numOfRows, numOfCols)
// your code there

}

object Matrix {
    def initMatrix(numOfRows:Int, numOfCols:Int) = Matrix(numOfRows, numOfCols)
}

var myMatrix = Matrix.initMatrix(3,5)

Upvotes: 1

Display Name
Display Name

Reputation: 8128

var matrix: Array[Array[Float]] = null — this declares a variable of the same type as yours

Upvotes: 1

Related Questions