Level 3 In-Depth AI · Math Foundations
Matrices and Matrix Multiplication
A matrix is a grid of numbers. It can hold a whole dataset, and it can transform vectors. A neural-network layer is one matrix multiplication, which is why GPUs, built to multiply matrices fast, power modern AI.
- Level
- ●●●●● Easy
- Reading
- 13 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 1 concept →
- Quiz
- 5 questions ↓
Read first
VectorsThe full path from zero — 1 concept before this one
- Vectors
- Matrices and Matrix Multiplication
Read them roughly in this order. See it on the concept map →
Why it matters
If you could look inside a running AI model, you would see one operation more than any other: multiplying matrices. A neural network layer takes a vector of inputs and multiplies it by a matrix of learned weights. A Transformer language model does this hundreds of times for each token it reads or writes. Attention is matrix multiplication. So are the embeddings lookup, the projections into queries, keys and values, and the final step that scores every word in the vocabulary.
This is not a detail. Graphics cards (GPUs) were designed to multiply matrices quickly for video games, and in the 2010s researchers discovered that the same chips could train neural networks dozens of times faster than ordinary processors. Modern AI chips are, at heart, matrix-multiplication machines, and their speed is quoted in how many multiply-and-add operations they do per second.
Matrices also hold data. A spreadsheet of 1,000 houses with 5 features each is a 1,000 × 5 matrix. A greyscale photo is a matrix of pixel brightnesses. Learning to read and multiply matrices is learning to read the source code of AI.
The intuition
A matrix is a rectangular grid of numbers, arranged in rows and columns. You can think of one in two ways.
As a table. Each row is one example and each column is one feature. Three houses with [size, rooms, age] make a matrix with 3 rows and 3 columns. Nothing more mysterious than a spreadsheet.
As a machine that transforms vectors. Feed a vector in, get a different vector out. A matrix can stretch space, squash it, rotate it, slant it, or flip it, as long as straight lines stay straight and the origin stays put. Such a transformation is called a linear transformation. Picture graph paper drawn on a rubber sheet. A matrix tells you how to pull the sheet. Every point on it moves, but the grid lines stay straight, parallel and evenly spaced.
The neat part is how little you need to know to describe the whole transformation. Just say where the two basic arrows go: (one step right) and (one step up). Write those two landing spots as the columns of a matrix, and you have it. Every other point follows, because every vector is a linear combination of and .
Key idea A matrix is a grid of numbers that transforms vectors. Multiplying a matrix by a vector takes a dot product of each row with the vector. A neural-network layer is exactly this: outputs = weight matrix × inputs.
How it works
Notation and shape
Matrices are written as bold capital letters: , , . A matrix with rows and columns has shape (say "m by n"). Rows always come first. The entry in row and column is written .
This is : 2 rows, 3 columns. (row 1, column 3) and .
A vector can be seen as a matrix with one column. An -component vector written standing up is an matrix, called a column vector.
Matrix times vector
To multiply a matrix by a vector, take the dot product of each row of the matrix with the vector. Each row produces one number of the result.
With :
A matrix takes a 3-component vector in and gives a 2-component vector out. The number of columns of the matrix must equal the length of the vector. Otherwise there is no way to pair up the numbers.
There is a second way to see the same calculation, the column view. is a linear combination of the columns of , weighted by the components of :
Same answer. The row view is how you compute it by hand. The column view explains the transformation picture: the columns are where the basic arrows land, and says how much of each to take.
A neural network layer
Here is why this matters so much. A layer of a neural network with 3 inputs and 2 outputs has 6 connections, each with a learned weight. Output 1 is a weighted sum of the three inputs, and so is output 2. Writing the weights into output as row of a matrix turns the whole layer into one line:
The vector holds one bias per output, a number added on regardless of the input. With our example gives . A real network then applies a non-linear activation function to each output and passes the result to the next layer. Without that non-linearity, stacking layers would be pointless, because two matrix multiplications in a row are equivalent to a single one.
Real layers are big. One feed-forward layer of GPT-3 has a weight matrix of shape , about 600 million weights in a single matrix, and the model has 96 such layers plus attention.
Matrix times matrix
To multiply two matrices, multiply the first by each column of the second as if it were a vector, and place the results side by side. Equivalently: entry of the result is the dot product of row of the first matrix with column of the second.
The shape rule is the single most useful thing to memorise:
The inner sizes ( and ) must match, and they disappear. The outer sizes give the result. A matrix times a matrix gives . A times a is an error.
Three properties to know:
- Order matters. In general . Swap the two matrices above and you get . As transformations, "rotate then stretch" differs from "stretch then rotate".
- Grouping does not matter. . You can combine a chain of transformations into one matrix in advance.
- Cost. Multiplying an by an matrix takes multiply-and-add steps. Double every size and the work goes up eight times. That is why model size drives the cost of AI so hard (see Scaling Laws).
Whole batches at once
Models process many examples together. Stack a batch of input vectors as the rows of a matrix of shape . Then the whole layer, for all examples at once, is
with shape : one row of outputs per example. The is the transpose, explained next. One big matrix multiplication is far faster on a GPU than small ones, which is why training uses mini-batches.
Transpose
The transpose flips a matrix over its diagonal: rows become columns.
An matrix becomes . Transposes appear all the time to make shapes line up, as in above. The dot product of two column vectors can also be written : a times an gives a result, a single number.
Identity and inverse
The identity matrix has 1s on the diagonal and 0s elsewhere:
It is the "do nothing" transformation: for every , just as multiplying a number by 1 leaves it alone.
Some matrices can be undone. The matrix inverse is the transformation that reverses , so . Not every matrix has one. A matrix that squashes the plane flat onto a line has thrown information away, and nothing can bring it back. In machine learning you rarely compute inverses directly. They appear in formulas such as the closed-form solution of Linear Regression, but in code you call a solver, which is faster and more accurate.
In code
import numpy as np
W = np.array([[ 1, 0, 2],
[-1, 3, 1]], dtype=float) # 2 x 3 weight matrix
x = np.array([2.0, 1.0, 1.0]) # 3 inputs
b = np.array([0.5, -1.0]) # 2 biases
print(W.shape, x.shape) # (2, 3) (3,)
print(W @ x) # [4. 2.] matrix times vector
print(W @ x + b) # [4.5 1. ] a whole linear layer
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print(A @ B) # [[19 22] [43 50]]
print(B @ A) # [[23 34] [31 46]] order matters!
print(A.T) # [[1 3] [2 4]] transpose
print(np.eye(2) @ A) # [[1. 2.] [3. 4.]] identity changes nothing
# A batch of 4 inputs, one per row: (4, 3) @ (3, 2) -> (4, 2)
X = np.array([[2, 1, 1], [0, 0, 1], [1, 1, 1], [3, 0, 0]], dtype=float)
print(X @ W.T + b)
# [[ 4.5 1. ]
# [ 2.5 0. ]
# [ 3.5 2. ]
# [ 3.5 -4. ]]
The @ operator is matrix multiplication. Note that * is something else: it multiplies entry by entry, which needs equal shapes and is not matrix multiplication.
In PyTorch, nn.Linear is exactly the layer above. It stores the weight matrix with shape (out_features, in_features), which is why the formula has a transpose:
import torch
layer = torch.nn.Linear(in_features=3, out_features=2)
print(layer.weight.shape, layer.bias.shape) # torch.Size([2, 3]) torch.Size([2])
X = torch.randn(4, 3) # a batch of 4 examples
print(layer(X).shape) # torch.Size([4, 2])
print(torch.allclose(layer(X), X @ layer.weight.T + layer.bias)) # True
Common pitfalls
- Shape mismatch errors.
matmul: Input operand 1 has a mismatch in its core dimensionmeans the inner sizes differ. Print.shapeof both sides and apply the shape rule. Usually one side needs a transpose. *instead of@.A * Bmultiplies element by element. It gives a result of the same shape and no error when the shapes are equal, so the bug is silent.- Rows versus columns. Is your data matrix "one example per row" or "one per column"? Libraries such as scikit-learn and PyTorch expect one example per row. Many textbooks write one per column. Check before you trust a formula.
- Assuming order doesn't matter. and usually differ, and one of them may not even exist.
- Computing inverses.
np.linalg.inv(A) @ bis slower and less accurate thannp.linalg.solve(A, b), and fails badly when the matrix is close to having no inverse.
Watch out A wrong transpose often doesn't crash. With a square weight matrix,
x @ Wandx @ W.Tboth run and both produce outputs of the right shape. Only one is the layer you meant. When a from-scratch implementation trains badly, check every transpose against the shape rule written out by hand.
Where it leads
- Tensors and Shapes extend matrices to three or more axes, such as a batch of images with shape (batch, channels, height, width).
- Eigenvectors and SVD finds the special directions in which a matrix only stretches, and breaks any matrix into simple pieces. This underlies PCA and Dimensionality Reduction and LoRA.
- Neural Networks stack matrix multiplications with activation functions in between. Backpropagation computes gradients that are themselves matrices of the same shapes.
- Attention compares every query with every key in one matrix product, .
- Recommender Systems factor a huge users × items rating matrix into the product of two thin matrices.
- Quantization stores weight matrices with fewer bits so that the multiplications are cheaper.
A bit of history
Grids of numbers for solving systems of equations appear in the Chinese text The Nine Chapters on the Mathematical Art, compiled around 2,000 years ago. The word "matrix" was introduced by James Joseph Sylvester in 1850, and Arthur Cayley defined matrix multiplication and the inverse in 1858, treating matrices as objects in their own right. In 1925 Werner Heisenberg's quantum mechanics turned out to be matrix algebra, which brought matrices into mainstream physics. For computing, the key moments were the BLAS libraries of the 1970s and 1980s, which standardised fast matrix routines, and then GPUs. In 2012 AlexNet won the ImageNet competition by running its matrix multiplications on two gaming GPUs, and the deep-learning boom followed.
Try it
- By hand, compute . Draw the input and the output arrows. What did the matrix do?
- You have a batch of 32 images, each flattened to 784 numbers, and a layer with 128 outputs. What are the shapes of , (PyTorch convention) and the output? How many weights does the layer have?
- Check in NumPy that for two random matrices of shapes and .
Hint for 1: the result is . Look at the angle between the two arrows. The columns of the matrix tell you where and go.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Essence of Linear Algebra
A visual intuition for vectors, matrices, determinants and eigenvectors. You will see the ideas, not just the rules.
Linear Algebra
Patient video lessons with exercises on vectors, matrices and transformations.
Immersive Linear Algebra
A free linear algebra book whose figures you can drag and rotate. Excellent for seeing vectors, dot products and matrices as geometry.
MIT 18.06: Linear Algebra
The classic university linear algebra course, with full video lectures, notes and problem sets. Strang explains matrices as things that act on vectors.
Mathematics for Machine Learning
The linear algebra, calculus, probability and optimisation that ML uses, in one free book.
Linear Algebra Review and Reference
A compact 30-page summary of exactly the linear algebra used in machine learning, with ML notation. A good reference once the ideas make sense.
NumPy: the absolute basics for beginners
The official, friendly introduction to arrays, shapes, indexing and broadcasting.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/math/matrices.md