Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 930
Alex L Avatar asked Aug 02 '14 09:08

Alex L


2 Answers

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 
}
like image 120
tabdulradi Avatar answered Sep 26 '22 09:09

tabdulradi


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

like image 22
elm Avatar answered Sep 23 '22 09:09

elm