首页 > 解决方案 > Scala中的矩阵向​​量乘法

问题描述

我有一个大小为 D的矩阵(实现为 List[List[Int]])和一个大小为D 的向量(实现为 List[Int])。假设D = 3的值,我可以通过以下方式创建矩阵和向量。

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

我可以将这两个乘以

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

此代码将矩阵与向量相乘,并根据需要返回向量。我想问有没有更快或最优的方法来使用 Scala 函数风格获得相同的结果?在我的场景中,我的D价值要大得多。

标签: scalafunctional-programming

解决方案


这样的事情呢?

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

推荐阅读