2015-07-10 224 views
-2

我有一個python代碼,這是預計輸出矩陣完全相同的大小的輸入矩陣。 [i,j]處的輸出值應等於d [i-1,j]和d [i,j]之和的兩倍,並將實例[i-1,j]處的輸出添加到它。我的代碼如下Python矩陣循環

import numpy as np 

d=((2,3,5,6),(4,6,7,9),(8,4,7,3),(1,7,3,9),(5,8,2,6)) 
d=np.matrix(d) 
r,c = np.shape(d) 

temp=[] 
y=[] 
y.append([0,0,0,0]) 

for i in range (r-1): 
    ro = d[i:i+2,:]  #fetch 2 rows at a time i.e. i and i+1 
    for j in range (c):   
     col = ro[:,j] #fetch 1 column of the row 
     v1 = int(col[0]) 
     v2 = int(col[1]) 
     x = (v1+v2)*2+int(y[i][j]) 
     temp.append(x) 
    y.append(temp) 
y = np.matrix(y) 
print y 

預計產量

[[0,0,0,0] 
[12,18,24,30] 
[36,38,52,54] 
[54,60,72,78] 
[66,90,82,108]] 

而是我得到:

[[[0, 0, 0, 0] 
    [12, 18, 24, 30, 36, 38, 52, 54, 30, 40, 44, 54, 24, 48, 34, 60] 
    [12, 18, 24, 30, 36, 38, 52, 54, 30, 40, 44, 54, 24, 48, 34, 60] 
    [12, 18, 24, 30, 36, 38, 52, 54, 30, 40, 44, 54, 24, 48, 34, 60] 
    [12, 18, 24, 30, 36, 38, 52, 54, 30, 40, 44, 54, 24, 48, 34, 60]]] 

哪裏是我的代碼中的錯誤?

+2

您對預期(和實際)輸出的定義不足。現在我需要進行逆向工程,我不想那樣做。 – runDOSrun

回答

1

你有外循環的每個迭代復位temp累加器。因此,代碼看起來:

... 

for i in range (r-1): 
    ro = d[i:i+2,:]  #fetch 2 rows at a time i.e. i and i+1 
    temp = [] # <------------- 
    for j in range (c): 

     ... 

你與原代碼得到了意想不到的輸出是因爲這樣Python列表的工作:當你的對象追加到Python的列表,只是一個參考該對象被存儲,而不是該對象的副本。所以,你的循環結束後,列表y樣子:

[reference to [0,0,0,0], 
reference to list created at line 7, 
reference to list created at line 7, 
reference to list created at line 7, 
reference to list created at line 7] 

所以最後四個引用都是爲了同一個目標!

+0

thanx很多@moarningsun ...還有你的詳細解釋 – ita

1

這看起來像是你可以用numpy的切片做:

dout = np.zeros_like(d) 
dout[1:,:] = (d[:-1] + d[1:])*2 
dout[1:,:] += dout[:-1,:] 

給出dout

matrix([[ 0, 0, 0, 0], 
     [ 12, 18, 24, 30], 
     [ 36, 38, 52, 54], 
     [ 54, 60, 72, 78], 
     [ 66, 90, 82, 108]]) 
+0

謝謝@ xnx ..但是你能幫我解釋一下浮動值的工作原理嗎? – ita

+0

如果你想讓'dout'具有浮點元素,只需使用'dout = np.zeros_like(d,dtype = float)'。 – xnx