{"course":{"slug":"maths-you-need","title":"The Maths You Actually Need","url":"https://addaly.com/learn/maths-you-need","level":"intermediate","track":"deep"},"lesson":{"slug":"graphs-as-matrices","title":"A graph is a matrix, and its paths are its powers","url":"https://addaly.com/learn/maths-you-need/graphs-as-matrices","position":64,"of":76,"minutes":9,"answer":"A graph's adjacency matrix turns paths into matrix powers and random walks into repeated multiplication whose fixed point is the leading eigenvector, which is PageRank.","keyIdea":"A graph's adjacency matrix turns paths into matrix powers and random walks into repeated multiplication whose fixed point is the leading eigenvector, which is PageRank, and a graph neural network layer is simply that matrix averaging each node's neighbours before a learned linear map."},"body":{"format":"markdown","text":"## Nodes, edges, and a grid of zeros and ones\n\nA graph is a set of things and a set of connections between them: pages and links, users and follows, papers and citations, atoms and bonds. Write the things down the side and across the top of a grid, put a 1 wherever two are connected and a 0 elsewhere, and you have the **adjacency matrix**. Everything in module 2 now applies to it.\n\nFour nodes in a square, 1 joined to 2, 2 to 3, 3 to 4, 4 to 1:\n\n```\n      1  2  3  4\n  1 [ 0  1  0  1 ]\n  2 [ 1  0  1  0 ]\n  3 [ 0  1  0  1 ]\n  4 [ 1  0  1  0 ]\n```\n\nThe row sums are the **degrees**, how many neighbours each node has: 2 each. For a directed graph the matrix need not be symmetric; a link from 1 to 2 puts a 1 in row 1, column 2, and nothing in row 2, column 1.\n\n## Paths are powers\n\nMultiply the matrix by itself. Entry `(i, j)` of `A²` is the dot product of row `i` with column `j`, which counts the nodes `k` such that `i` connects to `k` and `k` connects to `j`: the number of two-step paths from `i` to `j`. For the square:\n\n```\n        1  2  3  4\n  1  [  2  0  2  0 ]\n  2  [  0  2  0  2 ]\n  3  [  2  0  2  0 ]\n  4  [  0  2  0  2 ]\n```\n\nTwo two-step paths from 1 to 3, via 2 and via 4; two from 1 back to itself, out and back along either edge; none from 1 to 2, which is an odd number of steps away. `A³` counts three-step paths, and in general `A^k` counts walks of length `k`. Whether two nodes are connected at all is whether any power has a non-zero entry between them. That is how \"friends of friends\" and \"papers citing papers that cite this one\" are computed: one matrix multiply per hop.\n\n## Random walks and the vector that stops changing\n\nDivide each row by its degree and the matrix becomes a **transition matrix** `P`: entry `(i, j)` is the probability that a walker at `i` steps to `j`. Multiply a probability vector by `P` and you get where the walker is expected to be one step later. Do it again and again, and for most graphs the vector settles to one that no longer changes, the **stationary distribution**: the fraction of time a long random walk spends at each node.\n\nThree pages: A links to B and C, B links to C, C links to A.\n\n```\nstart:   (1/3, 1/3, 1/3)\nstep 1:  (0.333, 0.167, 0.500)\nstep 2:  (0.500, 0.167, 0.333)\nstep 3:  (0.333, 0.250, 0.417)\n   ...\nlimit:   (0.400, 0.200, 0.400)\n```\n\nThe walker spends 40 per cent of its time at A and at C and 20 per cent at B. That vector is the eigenvector of `P` with eigenvalue 1, module 2's \"direction the matrix does not turn\", and repeated multiplication finds it because every other component decays.\n\nThis is PageRank, before its one refinement: with probability 0.15 per step the walker jumps to a random page, which stops it being trapped in a page with no outgoing links or circling forever in a closed loop. The refinement changes the matrix slightly and the arithmetic not at all. Google's original ranking was the stationary distribution of a random walk on the web, computed by repeated multiplication of a matrix with a few billion rows.\n\n## Sparse, or it does not exist\n\nA graph with a billion nodes has an adjacency matrix with `10^18` entries. Nobody stores that; as float32 it is four million terabytes. But the web has perhaps a hundred links per page, so only `10^11` entries are non-zero, a ten-millionth of the matrix. Store the edge list, `(from, to)` pairs, and multiply by iterating the edges: the cost is the number of edges, not the square of the nodes. Module 1's sparse-versus-dense distinction is the whole difference between a computation that takes a minute and one that cannot start.\n\n## A graph neural network is one matrix multiply\n\nGive each node a feature vector and stack them as rows of a matrix `X`. Then `A X` replaces each node's features with the sum of its neighbours' features, and `D^(−1) A X`, dividing by degree, with the average. Follow that with a weight matrix and a nonlinearity:\n\n```\nX_next = ReLU( D^(−1) A X W )\n```\n\nThat is a graph convolution layer: average your neighbours, then apply a learned linear map. Stack `k` of them and each node has seen information from `k` hops away, which is `A^k` again. The models that predict molecular properties, detect fraud rings and recommend friends are variations on this one line, and the adjacency matrix is the part that makes them graph models rather than ordinary ones.\n\n## Doing it yourself\n\n```python\nimport numpy as np\nA = np.array([[0,1,0,1],[1,0,1,0],[0,1,0,1],[1,0,1,0]])\nprint(A @ A)                                 # two-step path counts\nP = A / A.sum(axis=1, keepdims=True)         # transition matrix\nv = np.ones(4) / 4\nfor _ in range(50): v = v @ P                # random walk\nprint(v)                                     # stationary distribution\n```\n\nThe `networkx` library does all of this for real graphs, free, on a laptop, and its `pagerank` function is the loop above with the jump added. The value of having done it by hand once is that every graph algorithm you meet afterwards reads as a matrix operation you already know."},"check":{"question":"For an adjacency matrix A, what does the entry in row 2, column 5 of A³ count?","options":[{"text":"Whether node 2 and node 5 are connected by an edge, cubed.","correct":false,"tempting":"Powers of the matrix are not powers of the entries; each multiplication composes a step, so A³ is about three-step walks."},{"text":"The number of nodes within three hops of node 2.","correct":false,"tempting":"That would be a row sum over a reachability matrix; a single entry concerns one destination, node 5, not a count of nodes."},{"text":"The number of walks of exactly three steps from node 2 to node 5.","correct":true},{"text":"The probability that a random walker starting at 2 is at 5 after three steps.","correct":false,"tempting":"Probabilities come from the transition matrix, rows divided by degree; the raw adjacency matrix counts walks rather than weighting them."}]},"prev":{"slug":"hashing-and-the-birthday-bound","title":"Hashing, collisions, and the square-root law behind them","url":"https://addaly.com/learn/maths-you-need/hashing-and-the-birthday-bound"},"next":{"slug":"nearest-neighbour-search-arithmetic","title":"Finding the closest vector among ten million: the arithmetic of approximate search","url":"https://addaly.com/learn/maths-you-need/nearest-neighbour-search-arithmetic"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'A graph is a matrix, and its paths are its powers', in The Maths You Actually Need. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/maths-you-need/graphs-as-matrices (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"A graph is a matrix, and its paths are its powers","courseTitle":"The Maths You Actually Need","module":{"index":7,"slug":"cost-and-scale","title":"Counting the cost: complexity and the arithmetic of scale"},"answer":null,"keyIdea":"A graph’s adjacency matrix turns paths into matrix powers and random walks into repeated multiplication whose fixed point is the leading eigenvector, which is PageRank, and a graph neural network layer is simply that matrix averaging each node’s neighbours before a learned linear map.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"nodes-edges-and-a-grid-of-zeros-and-ones","runs":[{"text":"Nodes, edges, and a grid of zeros and ones"}]},{"t":"p","runs":[{"text":"A graph is a set of things and a set of connections between them: pages and links, users and follows, papers and citations, atoms and bonds. Write the things down the side and across the top of a grid, put a 1 wherever two are connected and a 0 elsewhere, and you have the "},{"text":"adjacency matrix","b":true},{"text":". Everything in module 2 now applies to it."}]},{"t":"p","runs":[{"text":"Four nodes in a square, 1 joined to 2, 2 to 3, 3 to 4, 4 to 1:"}]},{"t":"code","lang":"","label":"Text","text":"      1  2  3  4\n  1 [ 0  1  0  1 ]\n  2 [ 1  0  1  0 ]\n  3 [ 0  1  0  1 ]\n  4 [ 1  0  1  0 ]"},{"t":"p","runs":[{"text":"The row sums are the "},{"text":"degrees","b":true},{"text":", how many neighbours each node has: 2 each. For a directed graph the matrix need not be symmetric; a link from 1 to 2 puts a 1 in row 1, column 2, and nothing in row 2, column 1."}]},{"t":"h2","id":"paths-are-powers","runs":[{"text":"Paths are powers"}]},{"t":"p","runs":[{"text":"Multiply the matrix by itself. Entry "},{"text":"(i, j)","code":true},{"text":" of "},{"text":"A²","code":true},{"text":" is the dot product of row "},{"text":"i","code":true},{"text":" with column "},{"text":"j","code":true},{"text":", which counts the nodes "},{"text":"k","code":true},{"text":" such that "},{"text":"i","code":true},{"text":" connects to "},{"text":"k","code":true},{"text":" and "},{"text":"k","code":true},{"text":" connects to "},{"text":"j","code":true},{"text":": the number of two-step paths from "},{"text":"i","code":true},{"text":" to "},{"text":"j","code":true},{"text":". For the square:"}]},{"t":"code","lang":"","label":"Text","text":"        1  2  3  4\n  1  [  2  0  2  0 ]\n  2  [  0  2  0  2 ]\n  3  [  2  0  2  0 ]\n  4  [  0  2  0  2 ]"},{"t":"p","runs":[{"text":"Two two-step paths from 1 to 3, via 2 and via 4; two from 1 back to itself, out and back along either edge; none from 1 to 2, which is an odd number of steps away. "},{"text":"A³","code":true},{"text":" counts three-step paths, and in general "},{"text":"A^k","code":true},{"text":" counts walks of length "},{"text":"k","code":true},{"text":". Whether two nodes are connected at all is whether any power has a non-zero entry between them. That is how “friends of friends” and “papers citing papers that cite this one” are computed: one matrix multiply per hop."}]},{"t":"h2","id":"random-walks-and-the-vector-that-stops-changing","runs":[{"text":"Random walks and the vector that stops changing"}]},{"t":"p","runs":[{"text":"Divide each row by its degree and the matrix becomes a "},{"text":"transition matrix","b":true},{"text":" "},{"text":"P","code":true},{"text":": entry "},{"text":"(i, j)","code":true},{"text":" is the probability that a walker at "},{"text":"i","code":true},{"text":" steps to "},{"text":"j","code":true},{"text":". Multiply a probability vector by "},{"text":"P","code":true},{"text":" and you get where the walker is expected to be one step later. Do it again and again, and for most graphs the vector settles to one that no longer changes, the "},{"text":"stationary distribution","b":true},{"text":": the fraction of time a long random walk spends at each node."}]},{"t":"p","runs":[{"text":"Three pages: A links to B and C, B links to C, C links to A."}]},{"t":"code","lang":"","label":"Text","text":"start:   (1/3, 1/3, 1/3)\nstep 1:  (0.333, 0.167, 0.500)\nstep 2:  (0.500, 0.167, 0.333)\nstep 3:  (0.333, 0.250, 0.417)\n   ...\nlimit:   (0.400, 0.200, 0.400)"},{"t":"p","runs":[{"text":"The walker spends 40 per cent of its time at A and at C and 20 per cent at B. That vector is the eigenvector of "},{"text":"P","code":true},{"text":" with eigenvalue 1, module 2’s “direction the matrix does not turn”, and repeated multiplication finds it because every other component decays."}]},{"t":"p","runs":[{"text":"This is PageRank, before its one refinement: with probability 0.15 per step the walker jumps to a random page, which stops it being trapped in a page with no outgoing links or circling forever in a closed loop. The refinement changes the matrix slightly and the arithmetic not at all. Google’s original ranking was the stationary distribution of a random walk on the web, computed by repeated multiplication of a matrix with a few billion rows."}]},{"t":"h2","id":"sparse-or-it-does-not-exist","runs":[{"text":"Sparse, or it does not exist"}]},{"t":"p","runs":[{"text":"A graph with a billion nodes has an adjacency matrix with "},{"text":"10^18","code":true},{"text":" entries. Nobody stores that; as float32 it is four million terabytes. But the web has perhaps a hundred links per page, so only "},{"text":"10^11","code":true},{"text":" entries are non-zero, a ten-millionth of the matrix. Store the edge list, "},{"text":"(from, to)","code":true},{"text":" pairs, and multiply by iterating the edges: the cost is the number of edges, not the square of the nodes. Module 1’s sparse-versus-dense distinction is the whole difference between a computation that takes a minute and one that cannot start."}]},{"t":"h2","id":"a-graph-neural-network-is-one-matrix-multiply","runs":[{"text":"A graph neural network is one matrix multiply"}]},{"t":"p","runs":[{"text":"Give each node a feature vector and stack them as rows of a matrix "},{"text":"X","code":true},{"text":". Then "},{"text":"A X","code":true},{"text":" replaces each node’s features with the sum of its neighbours’ features, and "},{"text":"D^(−1) A X","code":true},{"text":", dividing by degree, with the average. Follow that with a weight matrix and a nonlinearity:"}]},{"t":"code","lang":"","label":"Text","text":"X_next = ReLU( D^(−1) A X W )"},{"t":"p","runs":[{"text":"That is a graph convolution layer: average your neighbours, then apply a learned linear map. Stack "},{"text":"k","code":true},{"text":" of them and each node has seen information from "},{"text":"k","code":true},{"text":" hops away, which is "},{"text":"A^k","code":true},{"text":" again. The models that predict molecular properties, detect fraud rings and recommend friends are variations on this one line, and the adjacency matrix is the part that makes them graph models rather than ordinary ones."}]},{"t":"h2","id":"doing-it-yourself","runs":[{"text":"Doing it yourself"}]},{"t":"code","lang":"python","label":"Python","text":"import numpy as np\nA = np.array([[0,1,0,1],[1,0,1,0],[0,1,0,1],[1,0,1,0]])\nprint(A @ A)                                 # two-step path counts\nP = A / A.sum(axis=1, keepdims=True)         # transition matrix\nv = np.ones(4) / 4\nfor _ in range(50): v = v @ P                # random walk\nprint(v)                                     # stationary distribution"},{"t":"p","runs":[{"text":"The "},{"text":"networkx","code":true},{"text":" library does all of this for real graphs, free, on a laptop, and its "},{"text":"pagerank","code":true},{"text":" function is the loop above with the jump added. The value of having done it by hand once is that every graph algorithm you meet afterwards reads as a matrix operation you already know."}]}],"check":{"question":[{"text":"For an adjacency matrix A, what does the entry in row 2, column 5 of A³ count?"}],"options":[{"text":[{"text":"Whether node 2 and node 5 are connected by an edge, cubed."}],"correct":false,"tempting":[{"text":"Powers of the matrix are not powers of the entries; each multiplication composes a step, so A³ is about three-step walks."}]},{"text":[{"text":"The number of nodes within three hops of node 2."}],"correct":false,"tempting":[{"text":"That would be a row sum over a reachability matrix; a single entry concerns one destination, node 5, not a count of nodes."}]},{"text":[{"text":"The number of walks of exactly three steps from node 2 to node 5."}],"correct":true,"tempting":null},{"text":[{"text":"The probability that a random walker starting at 2 is at 5 after three steps."}],"correct":false,"tempting":[{"text":"Probabilities come from the transition matrix, rows divided by degree; the raw adjacency matrix counts walks rather than weighting them."}]}],"order":[3,0,1,2],"why":null},"prev":{"slug":"hashing-and-the-birthday-bound","title":"Hashing, collisions, and the square-root law behind them","minutes":9},"next":{"slug":"nearest-neighbour-search-arithmetic","title":"Finding the closest vector among ten million: the arithmetic of approximate search","minutes":10}}}