如果您有能力在进行计算之前使矩阵对称,那么以下应该相当快:
def symmetrize(a):
"""
Return a symmetrized version of NumPy array a.
Values 0 are replaced by the array value at the symmetric
position (with respect to the diagonal), i.e. if a_ij = 0,
then the returned array a' is such that a'_ij = a_ji.
Diagonal values are left untouched.
a -- square NumPy array, such that a_ij = 0 or a_ji = 0,
for i != j.
"""
return a + a.T - numpy.diag(a.diagonal())
这在合理的假设下有效(例如在运行 symmetrize 之前不同时执行 a[0, 1] = 42 和矛盾的 a[1, 0] = 123)。
如果您真的需要透明的对称化,您可以考虑继承 numpy.ndarray 并简单地重新定义 __setitem__:
class SymNDArray(numpy.ndarray):
"""
NumPy array subclass for symmetric matrices.
A SymNDArray arr is such that doing arr[i,j] = value
automatically does arr[j,i] = value, so that array
updates remain symmetrical.
"""
def __setitem__(self, (i, j), value):
super(SymNDArray, self).__setitem__((i, j), value)
super(SymNDArray, self).__setitem__((j, i), value)
def symarray(input_array):
"""
Return a symmetrized version of the array-like input_array.
The returned array has class SymNDArray. Further assignments to the array
are thus automatically symmetrized.
"""
return symmetrize(numpy.asarray(input_array)).view(SymNDArray)
# Example:
a = symarray(numpy.zeros((3, 3)))
a[0, 1] = 42
print a # a[1, 0] == 42 too!
(或使用矩阵代替数组的等价物,具体取决于您的需要)。这种方法甚至可以处理更复杂的赋值,例如 a[:, 1] = -1,它正确设置了 a[1, :] 元素。
请注意,Python 3 消除了编写 def …(…, (i, j),…) 的可能性,因此在使用 Python 3 运行之前必须稍微修改代码:def __setitem__(self, indexes, value): (i, j) = indexes...