我試圖如下定義的矩陣乘法函數:定義矩陣乘法;錯的行被修改
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 [0] [0],它也會同時將prod [1] [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]]
有人能解釋一下是什麼原因造成的?
如果你不知道它,Ruby有[Matrix](http://ruby-doc.org/stdlib-2.2.0/libdoc/matrix/rdoc/Matrix.html)和[Vector](http ://ruby-doc.org/stdlib-2.2.0/libdoc/matrix/rdoc/Vector.html)可能非常有用的類。多個兩個矩陣,例如:'require'matrix'; a = [[1,2,3],[4,5,6]]; b = [[1,2],[3,4],[5,6]]; m =矩陣[* a] *矩陣[* b]#=>矩陣[[22,28],[49,64]]; m.to_a#=> [[22,28],[49,64]]'。 –