How can multiplying two rail network matrices count two-leg journeys?
A rail map shows which stations you can reach directly. Now suppose your journey has two legs. If each set of links is written in a matrix, how can multiplying those matrices tell you how many ways there are to make the journey?
On this simplified rail map, the row is your starting station and the column is your destination. In row P, column Q, a one shows a direct link. The one in row Q, column P shows you can travel back. A zero means there’s no direct link for that pair.
Try two small number matrices, A and B. For the top-right entry of A B, take the blue top row of A and the orange right column of B. Multiply the first pair, one times one, then the second pair, two times four. Add one and eight to get nine.
Now use the same matrices to find the bottom-left entry. The second row of A is zero, one. The first column of B is three, two from top to bottom. Pick the calculation that puts the matching positions together.
Each station is a vertex, or node. Each mirrored pair of ones gives one undirected edge. Label P to Q with an extra weight of four minutes. P to Q to R is a path; return to P for a cycle. These three vertices are connected. Add isolated S and the graph is disconnected.
The position picks a row from A and a column from B. Across the top, one times three plus two times two gives seven; one times one plus two times four gives nine. Across the bottom, zero times three plus one times two gives two; zero times one plus one times four gives four.
Try a different pair of matrices. Row two of A contains one and three. Column one of B contains one and two, from top to bottom. What goes in row two, column one of the product? Pick your answer.
Compare the top-right results for the matrices in the worked example. Entry-by-entry multiplication uses only the top-right number from each matrix, so it gives two. Matrix multiplication uses the whole top row of A and the whole right column of B, so it gives nine.
Enter the two three-by-three matrices as NumPy arrays. The at sign multiplies them, and the printed result starts with two. Check by hand: zero times zero, plus one times one, plus one times one, gives two. Python counts from zero, so compare with C at index zero, zero.
Read both matrices in station order P, Q, R. In A, there’s an arc from P to R with no reverse arc, so the graph is directed. For the top-left entry, follow one link from A, then one from B. You can return to P via Q or via R, so the entry is two.