Search code examples
pythonnetworkx

Modifying adjacency matrix based on edges


I have the adjacency matrix, H of a graph. I delete the first and last rows and columns to generate a new matrix, H1. In H1, I would like to replace the diagonal with number of edges each vertex has with a negative sign. The graph, the current and desired outputs follow

enter image description here

import numpy as np
H = np.array([
    [0, 1, 0, 1, 0],
    [1, 0, 1, 1, 1],
    [0, 1, 0, 1, 1],
    [1, 1, 1, 0, 0],
    [0, 1, 1, 0, 0]
])

H1 = H[1:-1, 1:-1]
print([H1])

Current output:

array([[0, 1, 1],
       [1, 0, 1],
       [1, 1, 0]])]

Desired output:

array([[-2, 1, 1],
       [1, -2, 1],
       [1, 1, -2]])]

Solution

  • You can use numpy.identity and numpy.ndarray.sum to achieve that. I.e.

    >>> H1 - np.identity(3)*H1.sum(axis=1)
    array([[-2.,  1.,  1.],
           [ 1., -2.,  1.],
           [ 1.,  1., -2.]])