我正在尝试定义矩阵乘法函数,如下所示:
def matrix_mult(a, b)
#a is mxn, b is nxq, so prod of a and b is mxq
m = a.length; n = a[0].length;
n = b.length; q = b[0].length;
prod=Array.new(m, Array.new(q,0));
(0...m).each do |i|
(0...q).each do |j|
#dot i-th row of m with j-th row of n:
(0...n).each {|k| prod[i][j]+=(a[i][k])*(b[k][j])}
#puts "i="+i.to_s
#puts "j="+j.to_s
#print prod; print "\n"
end
end
return prod
end
在2乘2样本上进行测试时,在第一次迭代中(其中i = j = 0),变量“k”的行正确计算prod [0] [0]。但是,它同时将prod [1] [0]设置为相同的值,即使该块只应修改prod [0] [0]。类似地,当i = 0且j = 1时,我得到prod [0] [1]的正确值,但prod [1] [1]同时被修改。
以下是我所得到的一个示例,用于说明问题:
a=[[1, 2], [3, 2]]; b=[[3, 2], [1, 1]])
##output below
i =0
j =0
[[5, 0], [5, 0]] ##I don't know why the second row was made [5,0]
i =0
j =1
[[5, 4], [5, 4]]
i =1
j =0
[[16, 4], [16, 4]]
i =1
j =1
[[16, 12], [16, 12]]
有人可以解释导致这种情况的原因吗?
答案 0 :(得分:1)
如果您按如下方式修改def
的开头,则会发现它有效:
def matrix_mult(a, b)
#a is mxn, b is nxq, so prod of a and b is mxq
m = a.length; n = a[0].length;
n = b.length; q = b[0].length;
prod=Array.new(m,0);
(0...m).each do |i|
prod[i] = Array.new(q,0);
(0...q).each do |j|
....
由于您的prod
是一个数组数组,因此每个顶级元素必须是单独的数组。
还应该做出另外一项重要的改变。您的代码设置n
两次,而它应该检查是否满足先决条件。