Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upper Triangular Matrix in Scala

Is there a way I can perform a faster computation of upper triangle matrix in scala?

/** Returns a vector which consists of the upper triangular elements of a matrix */   
def getUpperTriangle(A: Array[Array[Double]]) = 
{
    var A_ = Seq(0.)
    for (i <- 0 to A.size - 1;j <- 0 to A(0).size - 1)
    {
        if (i <= j){
            A_ = A_ ++ Seq(A(i)(j))
            }
    }
    A_.tail.toArray
}
like image 250
Alger Remirata Avatar asked Apr 29 '26 16:04

Alger Remirata


1 Answers

I don't know about faster, but this is a lot shorter and more "functional" (I note you tagged your question with functional-programming)

def getUpperTriangle(a: Array[Array[Double]]) = 
   (0 until a.size).flatMap(i => a(i).drop(i)).toArray

or, more or less same idea:

def getUpperTriangle(a: Array[Array[Double]]) =
   a.zipWithIndex.flatMap{case(r,i) => r.drop(i)}
like image 52
The Archetypal Paul Avatar answered May 01 '26 05:05

The Archetypal Paul