What matrix multiplication is
Multiplying two matrices is not the same as multiplying two numbers. You cannot simply multiply matching positions. Instead, each entry of the result is a dot product of one row from the left matrix and one column from the right matrix. That single rule explains the shapes, the order requirement and almost every confusion beginners hit.
If A is m × n and B is n × p, the product AB is m × p. The inner dimensions must match — the n in both — and the outer dimensions give the result's shape.
The row-by-column rule
To fill position (i, j) of the result, take row i of the left matrix, take column j of the right matrix, multiply the pairs element by element, and add the products:
result[i][j] = Σₖ A[i][k] × B[k][j]
That is all matrix multiplication is. The visualiser above animates exactly this loop, one row and column at a time, so you can watch which numbers are being combined.
A worked 2×2 example
Take A = [[1, 2], [3, 4]] and B = [[5, 6], [7, 8]]. The top-left entry of AB is row 1 of A times column 1 of B: 1×5 + 2×7 = 19. The top-right is 1×6 + 2×8 = 22. Continuing, AB = [[19, 22], [43, 50]].
Note that BA = [[23, 34], [31, 46]] — different numbers entirely. Matrix multiplication is not commutative, which is why the order of factors matters in every formula that uses it.
Why it matters in machine learning
Almost every neural network operation is a matrix multiplication in disguise. A dense layer computes y = Wx + b, where W is a weight matrix. Attention in a transformer is built from three of them — queries, keys and values — multiplied together to score every token against every other token. Graphics pipelines, recommender systems and PCA all reduce to the same row-by-column pattern.
Understanding the shape rules is what lets you debug a neural network: when a layer throws a dimension mismatch, the inner dimensions of the two matrices you are multiplying do not agree.
Frequently asked questions
Can you multiply any two matrices?
No. The number of columns in the left matrix must equal the number of rows in the right matrix. If A is 3×4 and B is 4×2, AB works and is 3×2; BA does not exist.
Does the order of multiplication matter?
Yes. AB and BA are usually different, and one may not even be defined. Matrix multiplication is associative — (AB)C = A(BC) — but not commutative.
What is the identity matrix used for?
The identity matrix has ones on the diagonal and zeros elsewhere. Multiplying any matrix by it returns the original matrix unchanged, the way multiplying a number by 1 does.
How is matrix multiplication used in neural networks?
Each dense layer multiplies its input by a weight matrix and adds a bias vector. Transformers stack several such multiplications to compute attention scores and outputs.
