1

I'm using the code below to generate some random Euclidean graphs. I expected the adjacency matrix to have the distances between nodes rather than just being a binary representation of the connections. How do I make the adjacency matrix hold the actual distances/weights between nodes?

g = nx.generators.random_geometric_graph(n, 10)
adj = nx.adjacency_matrix(g).todense()

1 Answer 1

1

Well, the adjacency matrix denotes the adjacency, not a distance. To get the distances, you can grab the pos attribute of the nodes, and proceed normally:

g = nx.generators.random_geometric_graph(10, 0.1)
pos = np.array([g.nodes[node]['pos'] for node in g.nodes])
delta = pos[np.newaxis, :, :] - pos[:, np.newaxis, :]
distances = = np.sqrt(np.sum(delta**2, axis=-1))
Sign up to request clarification or add additional context in comments.

2 Comments

If you were going to set the weight attributes on the edges, would you do it this same way?
In that case, you may be only interested in the distances between connected nodes. If the graph is small, computing the distances between all nodes is fine, but if the graph is very large, you might want to only compute the distances between connected pairs of nodes (i.e. loop over edges, get the node positions, compute the distance, set edge weight, etc).

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.