user346206
user346206

Reputation: 313

Convert adjacency matrix to array of edges

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?

Upvotes: 0

Views: 112

Answers (4)

mozway
mozway

Reputation: 260300

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]]

Upvotes: 2

John Coleman
John Coleman

Reputation: 51988

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]]

Upvotes: 0

PlainRavioli
PlainRavioli

Reputation: 1211

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

Upvotes: 1

funnydman
funnydman

Reputation: 11326

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]]

Upvotes: 0

Related Questions