-1

I have a file which contains the edges for the matrix. For example, location (1, 2) in the adjacency matrix generated from the file is 2, as the pair 1 2 occurs twice in the graph.

I need to make a adjacency matrix from this using python and I am unsure how to do it.

the file is:

0 1 
1 2  1 2  1 3  1 3  1 4 
2 3 
3 0 
4 0  4 2 

the output should be:

[[0. 1. 0. 0. 0.]
[0. 0. 2. 2. 1.]
[0. 0. 0. 1. 0.]
[1. 0. 0. 0. 0.]
[1. 0. 1. 0. 0.]]

thank you!!

  • For every line in your file create a new row and then update that row's index with count of that index. – lllrnr101 Apr 10 '21 at 01:53

1 Answers1

0

You can try this:

s = """
0 1 
1 2  1 2  1 3  1 3  1 4 
2 3 
3 0 
4 0  4 2 
"""

import re
import numpy as np

# get an array with vertices of edges
a = np.array(re.findall(r"(\d+) (\d+)", s)).astype(int)
# compute the adjacency matrix
np.add.at(adj := np.zeros((n := a.max() + 1, n), dtype=int), tuple(a.T), 1)
print(adj)

It gives:

[[0 1 0 0 0]
 [0 0 2 2 1]
 [0 0 0 1 0]
 [1 0 0 0 0]
 [1 0 1 0 0]]
bb1
  • 7,174
  • 2
  • 8
  • 23