Return the graph adjacency matrix as a NumPy matrix.
Parameters: | G : graph
nodelist : list, optional
dtype : NumPy data type, optional
order : {‘C’, ‘F’}, optional
multigraph_weight : {sum, min, max}, optional
weight : string or None optional (default=’weight’)
nonedge : float (default=0.0)
|
---|---|
Returns: | M : NumPy matrix
|
See also
Notes
The matrix entries are assigned to the weight edge attribute. When an edge does not have a weight attribute, the value of the entry is set to the number 1. For multiple (parallel) edges, the values of the entries are determined by the ‘multigraph_weight’ paramter. The default is to sum the weight attributes for each of the parallel edges.
When \(nodelist\) does not contain every node in \(G\), the matrix is built from the subgraph of \(G\) that is induced by the nodes in \(nodelist\).
The convention used for self-loop edges in graphs is to assign the diagonal matrix entry value to the weight attributr of the edge (or the number 1 if the edge has no weight attribute). If the alternate convention of doubling the edge weight is desired the resulting Numpy matrix can be modified as follows:
>>> import numpy as np
>>> G = nx.Graph([(1,1)])
>>> A = nx.to_numpy_matrix(G)
>>> A
matrix([[ 1.]])
>>> A.A[np.diag_indices_from(A)] *= 2
>>> A
matrix([[ 2.]])
Examples
>>> G = nx.MultiDiGraph()
>>> G.add_edge(0,1,weight=2)
>>> G.add_edge(1,0)
>>> G.add_edge(2,2,weight=3)
>>> G.add_edge(2,2)
>>> nx.to_numpy_matrix(G, nodelist=[0,1,2])
matrix([[ 0., 2., 0.],
[ 1., 0., 0.],
[ 0., 0., 4.]])