Matrices and Their Connection to Graphs

  • A node set
  • An edge set
D
|
A - B - C
└-------┘
A  B  C  D
┌------------┐
A | 0 1 1 0 |
B | 1 0 1 1 |
C | 1 1 0 0 |
D | 0 1 0 0 |
└------------┘
import networkx as nx
import numpy as np
G = nx.Graph()
G.add_nodes_from(
[("A", "B"), ("B", "C"), ("A", "C"), ("B", "D")]
)
adj_mat = nx.to_adjacency_matrix(G)
# This is what adj_mat looks like
adj_mat
# output:
array([[0., 1., 1., 0.],
[1., 0., 1., 1.],
[1., 1., 0., 0.],
[0., 1., 0., 0.]])
(np.triu(adj_mat) == np.tril(adj_mat).T).all()
# evaluates to `True`
np.triu(adj_mat).sum()
# evalutes to 4.0
np.linalg.matrix_power(adj_mat, 2)
# output:
array([[2., 1., 1., 1.],
[1., 3., 1., 0.],
[1., 1., 2., 1.],
[1., 0., 1., 1.]])
np.diagonal(np.linalg.matrix_power(adj_mat, 2))
# output:
array([2., 3., 2., 1.])

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
ODSC - Open Data Science

ODSC - Open Data Science

94K Followers

Our passion is bringing thousands of the best and brightest data scientists together under one roof for an incredible learning and networking experience.