sseal
sseal

Reputation: 9

Building a graph in Python

I need to build a graph with 100 nodes and 200 edges from a random adjacency matrix. This matrix can contain only 0s and 1s. Obviously, I did something wrong because the graph I have right now is super weird.

G = nx.Graph()
ctr = 0
V = 100
E = 200
for i in range(0, V) :
   if(i == 200) :
       break
   for j in range(0, V) :
       if(i == j) :
          continue;
       if(ctr < E) :
          G.add_edge(i, j)
          ctr = ctr + 1

Can you help me with that, please? Would be really thankful for any suggestions

Upvotes: 0

Views: 71

Answers (2)

warped
warped

Reputation: 9481

Since you are using networkx anyway, you might want to convert the adjacency matrix directly into the graph:

# dummy 100 by 100 adj matrix:
am = np.zeros((10000))
am[np.random.choice(np.arange(10000), 200, replace=False)] = 1
am = am.reshape(100,100)

# use networkx functionality to build graph
G = nx.from_numpy_matrix(am)

Upvotes: 1

Vissarion Moutafis
Vissarion Moutafis

Reputation: 78

The proper way of doing the task you asked for is the following:


cnt = 0 # edge count
for i in range(0, V):
    if cnt > E:
        break
    for j in range(0, V):
        if adj_matrix[i][j] == 1: # if there is an edge according to the adjacency matrix
            G.add_edge(i, j)
            cnt += 1 # increase the edge count

You should check the adjacency matrix whether there is an edge or not and only that would be enough. You can comment for further details if you need more help with that.

Upvotes: 0

Related Questions