0

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

4
  • What does "super weird" mean? What results did you get and what do you expect instead? Are you suppsed to write code that expects an adjacency matrix as input? If so, you should add that part. Commented Sep 29, 2020 at 16:31
  • You can remove if(i == 200) : break because i will only be at maximum 99. Did you mean if(ctr == 200) :? Commented Sep 29, 2020 at 16:32
  • What do you mean by "random adjacency matrix"? Your code has no adjacency matrix and is not random. It will create a complete graph instead. Commented Sep 29, 2020 at 16:34
  • Instead of if(ctr < e) :, do you mean if(ctr < E) :? Please make sure your code runs as you expect when you post. Commented Sep 29, 2020 at 16:34

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.