Asif
Asif

Reputation: 733

Matrix Vector multiplication in Scala

I am having a Matrix of size D by D (implemented as List[List[Int]]) and a Vector of size D (implemented as List[Int]). Assuming value of D = 3, I can create matrix and vector in following way.

val Vector = List(1,2,3)
val Matrix = List(List(4,5,6) , List(7,8,9) , List(10,11,12))

I can multiply both these as

(Matrix,Vector).zipped.map((x,y) => (x,Vector).zipped.map(_*_).sum )

This code multiplies matrix with vector and returns me vector as needed. I want to ask is there any faster or optimal way to get the same result using Scala functional style? As in my scenario I have much bigger value of D.

Upvotes: 0

Views: 584

Answers (1)

What about something like this?

def vectorDotProduct[N : Numeric](v1: List[N], v2: List[N]): N = {
  import Numeric.Implicits._

  // You may replace this with a while loop over two iterators if you require even more speed.
  @annotation.tailrec
  def loop(remaining1: List[N], remaining2: List[N], acc: N): N =
    (remaining1, remaining2) match {
      case (x :: tail1, y :: tail2) =>
        loop(
          remaining1 = tail1,
          remaining2 = tail2,
          acc + (x * y)
        )

      case (Nil, _) | (_, Nil) =>
        acc
    }

  loop(
    remaining1 = v1,
    remaining2 = v2,
    acc = Numeric[N].zero
  )
}

def matrixVectorProduct[N : Numeric](matrix: List[List[N]], vector: List[N]): List[N] =
  matrix.map(row => vectorDotProduct(vector, row))

Upvotes: 2

Related Questions