【发布时间】:2017-02-24 22:47:31
【问题描述】:
我正在尝试制作一个需要矩阵邻居(不包括自身)和 ex 的程序:
matrix([[0, 0, 0],
[1, 0, 1],
[0, 1, 0]])
会返回:
matrix([[1, 2, 1],
[1, 3, 1],
[2, 2, 2]])
我在这里有一个工作代码,但它又大又乱,而且我是 numpy 的新手,所以我需要一些帮助来清理和优化它。 (我觉得必须有更好的方法)
示例代码:
import numpy as np
def NiSum(m):
new = []
for x in range(m.shape[0]-1):
row = []
for y in range(m.shape[1]-1):
Ni = 0
for a in [1,1],[1,0],[1,-1],[0,1],[0,-1],[-1,1],[-1,0],[-1,-1]:
Ni += m[x+a[0],y+a[1]]
row.append(Ni)
new.append(row)
return np.matrix(new)
example = np.matrix('0 0 0 0 0 0 0 0; '*3+'0 0 0 1 1 1 0 0; '*3+'0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 ')
NiSum(example)
感谢您的帮助!
【问题讨论】:
标签: python python-3.x numpy matrix scipy