Python矩阵循环

Python矩阵循环,python,numpy,Python,Numpy,我有一个python代码,它输出的矩阵与输入矩阵的大小完全相同。[i,j]处的输出值应等于d[i-1,j]和d[i,j]之和的两倍,并将实例[i-1,j]处的输出相加。我的代码如下 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

我有一个python代码,它输出的矩阵与输入矩阵的大小完全相同。[i,j]处的输出值应等于d[i-1,j]和d[i,j]之和的两倍,并将实例[i-1,j]处的输出相加。我的代码如下

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]]]

我的代码中的错误在哪里?

这似乎是可以通过numpy切片来完成的:

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

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

每次迭代外循环时,必须重置
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):

        ...

所以最后四个引用都指向同一个对象

您对预期(和实际)输出的定义不够充分。现在我需要对它进行反向工程,但我不想这样做。谢谢@xnx..但是你能帮我如何处理浮点值吗?只要使用
dout=np.zero\u like(d,dtype=float)
就可以了,如果你想
dout
有浮点元素。thanx很多@moarningsun…还有你的详细解释
[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]