Home > other >  Convert adjacency matrix to array of edges
Convert adjacency matrix to array of edges

Time:10-10

I want to be able to convert an adjacency matrix to array of edges. Currently I know only how to conver an array of edges to adjacency matrix:

E = [[0, 0], [0, 1], [1, 1], [2, 0]]
size = len(set([n for e in E for n in e]))
adjacency_matrix = [[0] * size for _ in range(size)]
for sink, source in E:
    adjacency_matrix[sink][source] = 1
>> print(adjacency_matrix)
[[1, 1, 0], [0, 1, 0], [1, 0, 0]]

but is there a possibility to reverse this process?

CodePudding user response:

Try this

E = np.stack(np.where(adjacency_matrix)).T

Add tolist() if you want a list

Output (with tolist())

[[0, 0], [0, 1], [1, 1], [2, 0]]

EDIT: my bad I thought OP was using numpy, so here it is in numpy

CodePudding user response:

If you need pure python, use a list comprehension:

adjacency_matrix = [[1, 1, 0], [0, 1, 0], [1, 0, 0]]

E = [[i,j] for i,l in enumerate(adjacency_matrix) for j, x in enumerate(l) if x]

output: [[0, 0], [0, 1], [1, 1], [2, 0]]

CodePudding user response:

Yes, it's possible and easy, just iterate through your matrix using two nested cycles, for example:

adjacency_matrix = [[1, 1, 0], [0, 1, 0], [1, 0, 0]]
E = []

for i in range(size):
    for j in range(size):
        if adjacency_matrix[i][j] == 1:
            E.append([i, j])

print(E)

Output:

[[0, 0], [0, 1], [1, 1], [2, 0]]

CodePudding user response:

You could make a function for it:

def adj_to_edges(A):
    edges = []
    for i,row in enumerate(A):
        for j,b in enumerate(row):
            if b == 1:
                edges.append([i,j])
    return edges

print(adj_to_edges([[1, 1, 0], [0, 1, 0], [1, 0, 0]]))
#[[0, 0], [0, 1], [1, 1], [2, 0]]
  • Related