Brannon
Brannon

Reputation: 5414

generate adjacency matrix via networkx that has weights

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()

Upvotes: 1

Views: 892

Answers (1)

Paul Brodersen
Paul Brodersen

Reputation: 13031

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

Upvotes: 1

Related Questions