如果您有能力在进行计算之前就对称矩阵,则以下操作应相当快:
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())
这在合理的假设下有效(例如,在运行之前不做任何事情a[0, 1] = 42
并且矛盾)。a[1, 0] = 123
symmetrize
如果您确实需要透明的对称化,则可以考虑子类化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)
a = symarray(numpy.zeros((3, 3)))
a[0, 1] = 42
print a
(或等价于矩阵而不是数组,具体取决于您的需求)。这种方法甚至可以处理更复杂的分配,例如a[:, 1] = -1
,可以正确设置a[1, :]
元素。
请注意,Python 3消除了编写的可能性def …(…, (i, j),…)
,因此在使用Python 3进行运行之前,必须对代码进行些微调整def __setitem__(self, indexes, value): (i, j) = indexes
。