Reputation: 13510
My question might sound stupid but how can I get the adjacency matrix of a directed graph?
Let me explain. I have the following code:
g = Graph()
g.add_vertices(5)
g.add_edges([(0,1),(1,2)])
print(g)
print(g.get_adjacency())
The first print returns:
IGRAPH U--- 5 2 --
+ edges:
0--1 1--2
While the second one returns:
[[0, 1, 0, 0, 0]
[1, 0, 1, 0, 0]
[0, 1, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]]
What if I want my graph to be directed and not undirected?
Thanks for the help
Upvotes: 0
Views: 5751
Reputation: 74172
You need to initalize your graph as directed before you start adding edges to it:
gd = Graph(directed=True)
gd.add_vertices(5)
gd.add_edges([(0,1),(1,2)])
print(gd.get_adjacency())
# [[0, 1, 0, 0, 0]
# [0, 0, 1, 0, 0]
# [0, 0, 0, 0, 0]
# [0, 0, 0, 0, 0]
# [0, 0, 0, 0, 0]]
The .to_directed()
method that Matthew mentioned won't do what you want, because it creates edges in both directions for each undirected edge:
print(g.is_directed()) # your original undirected example graph
# False
g.to_directed()
print(g.is_directed())
# True
print(g.get_adjacency()) # adjacency matrix is still symmetric
# [[0, 1, 0, 0, 0]
# [1, 0, 1, 0, 0]
# [0, 1, 0, 0, 0]
# [0, 0, 0, 0, 0]
# [0, 0, 0, 0, 0]]
You can prevent both directed edges from being created by passing .to_directed(mutual=False)
, but in this case igraph just picks an arbitrary single direction for each edge. The fundamental problem is that information about the directions of edges is simply not stored if the graph is undirected.
Upvotes: 2