从矩阵中减去转置但保留原始对角线

时间:2014-10-30 03:51:59

标签: python numpy matrix

我在numpy中有以下矩阵

mat = numpy.random.random_integers(0, 100, (3, 3))
        A   B   C
     A [69, 88, 64],
     B [92, 17, 35],
     C [ 8, 74, 39]

是否存在pythonic方式(即避免嵌套循环)从mat(B,A)中减去mat(A,B);席子(A,C)来自垫子(C,A)等......?对角元素可以单独留下。结果应该是:

        A       B     C
     A [69,   88-92, 64-8],
     B [92-88, 17,   35-74],
     C [8-64,  74-35, 39]

变为:

       A   B   C
     A [69, -4, 56],
     B [4, 17, -39],
     C [-56, 39, 39]

2 个答案:

答案 0 :(得分:4)

你可以轻松地完成非对角线术语:

>>> mat = np.array([[69, 88, 64], [92, 17, 35], [8, 74, 39]])
>>> mat
array([[69, 88, 64],
       [92, 17, 35],
       [ 8, 74, 39]])
>>> mat - mat.T
array([[  0,  -4,  56],
       [  4,   0, -39],
       [-56,  39,   0]])

要将对角线放回去,你可以做到

>>> m = (mat - mat.T) + np.diag(np.diag(mat))
>>> m
array([[ 69,  -4,  56],
       [  4,  17, -39],
       [-56,  39,  39]])

或者也许:

>>> m = (mat - mat.T)
>>> np.fill_diagonal(m, mat.diagonal())
>>> m
array([[ 69,  -4,  56],
       [  4,  17, -39],
       [-56,  39,  39]])

答案 1 :(得分:1)

mata = mat
matb = mat - matrix.transpose(mat)
for i in range(len(mat)):
     matb[i][i] = mata[i][i]

这些循环是否过于嵌套?