scala - 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价值要大得多。
解决方案
这样的事情呢?
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))
推荐阅读
- codemirror - file_put_content 在文件中添加空行
- javascript - 如何在 webdriverio 中获取表格特定元素的文本?
- python - 具有有效数据的最后一个单元格
- c# - 当我不想修改一个属性时,它不起作用,ef core的问题
- python - Python 字典的内存高效 Hashmap 替代方案(整数到整数)
- c - 使用 C 中的可变长度消息更新无锁缓冲区
- typo3 - 扩展“X”和插件“X”的默认控制器无法确定
- arrays - 如何在C中存储字节数组
- python - 如何解决单声道音频的无效形状
- ios - 调用实例方法“tableView”没有完全匹配