我正在为了娱乐和练习编写自己的矩阵模块(时间和空间复杂度不重要)。现在我想实现矩阵乘法,但我遇到了困难。可能是因为我使用了Haskell,而且我对它没有太多经验。这是我的数据类型:
data Matrix a =
M {
rows::Int,
cols::Int,
values::[a]
}
将以下3x2矩阵存储在数组中:
1 2
3 4
5 6
= [1,2,3,4,5,6]
我有一个基本可用的转置函数
transpose::(Matrix a)->(Matrix a)
transpose (M rows cols values) = M cols rows (aux values 0 0 [])
where
aux::[a]->Int->Int->[a]->[a]
aux values row col transposed
| cols > col =
if rows > row then
aux values (row+1) col (transposed ++ [valueAtIndex (M rows cols values) (row,col)])
else aux values 0 (col+1) transposed
| otherwise = transposed
为了对数组中的元素进行索引,我使用了这个函数。
valueAtIndex::(Matrix a)->(Int, Int)->a
valueAtIndex (M rows cols values) (row, col)
| rows <= row || cols <= col = error "indices too large for given Matrix"
| otherwise = values !! (cols * row + col)
据我理解,我需要获取这样的元素 m1: 2x3 和 m2: 3x2。
m1(0,0)*m2(0,0)+m1(0,1)*m2(0,1)+m1(0,2)*m2(0,2)
m1(0,0)*m2(1,0)+m1(0,1)*m2(1,1)+m1(0,2)*m2(1,2)
m1(1,0)*m2(0,0)+m1(1,1)*m2(0,1)+m1(1,2)*m2(0,2)
m1(1,0)*m2(1,0)+m1(1,1)*m2(1,1)+m1(1,2)*m2(2,2)
现在我需要一个函数,它接受两个矩阵,其中
m1 的行数等于 m2 的列数
,然后以某种递归的方式计算出正确的矩阵。multiplyMatrix::Num a=>(Matrix a)->(Matrix a)->(Matrix a)