◆ AI All-in-One

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 →
↗ Plan a path here

Read first

Vectors

This leads to

Convolutional Neural NetworksGraph Neural NetworksNeural NetworksSelf-Attention and Multi-Head AttentionEigenvectors and SVDTensors and ShapesRecommender SystemsGPUs and Why AI Needs ThemNumPy and Array Thinking
The full path from zero — 1 concept before this one
  1. Vectors
  2. 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.

A matrix transforms space. On the left, the ordinary grid with the two basic arrows e₁ and e₂ and a point at [1, 2]. The matrix M stretches and slants the grid. The columns of M, [2, 0] and [1, 1], are exactly where e₁ and e₂ end up, and the point lands at [4, 2].

The neat part is how little you need to know to describe the whole transformation. Just say where the two basic arrows go: e1=[1,0]\mathbf{e}_1 = [1, 0] (one step right) and e2=[0,1]\mathbf{e}_2 = [0, 1] (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 e1\mathbf{e}_1 and e2\mathbf{e}_2.

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: W\mathbf{W}, X\mathbf{X}, M\mathbf{M}. A matrix with mm rows and nn columns has shape m×nm \times n (say "m by n"). Rows always come first. The entry in row ii and column jj is written WijW_{ij}.

W=[102−131]\mathbf{W} = \begin{bmatrix} 1 & 0 & 2 \\ -1 & 3 & 1 \end{bmatrix}

This W\mathbf{W} is 2×32 \times 3: 2 rows, 3 columns. W13=2W_{13} = 2 (row 1, column 3) and W21=−1W_{21} = -1.

A vector can be seen as a matrix with one column. An nn-component vector written standing up is an n×1n \times 1 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.

1 0 2 −1 3 1 2 1 1 4 2 · = W 2 rows × 3 columns x 3 × 1 Wx 2 × 1 Each output = one row · the vector (a dot product) row 1: 1·2 + 0·1 + 2·1 = 4 row 2: −1·2 + 3·1 + 1·1 = 2 The shape rule (m × n) · (n × p) → (m × p) the inner sizes must match; the outer sizes give the result Examples (2 × 3) · (3 × 1) → (2 × 1) ✓ (2 × 3) · (2 × 1) → error ✗
Fig. 1 Multiplying a 2 × 3 matrix by a 3-component vector. Row 1 dotted with the vector gives 4. Row 2 dotted with the vector gives 2. The shape rule: the inner sizes must match, and the outer sizes give the shape of the result.

With x=[2,1,1]\mathbf{x} = [2, 1, 1]:

Wx=[102−131][211]=[1⋅2+0⋅1+2⋅1−1⋅2+3⋅1+1⋅1]=[42]\mathbf{W}\mathbf{x} = \begin{bmatrix} 1 & 0 & 2 \\ -1 & 3 & 1 \end{bmatrix} \begin{bmatrix} 2 \\ 1 \\ 1 \end{bmatrix} = \begin{bmatrix} 1 \cdot 2 + 0 \cdot 1 + 2 \cdot 1 \\ -1 \cdot 2 + 3 \cdot 1 + 1 \cdot 1 \end{bmatrix} = \begin{bmatrix} 4 \\ 2 \end{bmatrix}

A 2×32 \times 3 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. Wx\mathbf{W}\mathbf{x} is a linear combination of the columns of W\mathbf{W}, weighted by the components of x\mathbf{x}:

2[1−1]+1[03]+1[21]=[42]2 \begin{bmatrix} 1 \\ -1 \end{bmatrix} + 1 \begin{bmatrix} 0 \\ 3 \end{bmatrix} + 1 \begin{bmatrix} 2 \\ 1 \end{bmatrix} = \begin{bmatrix} 4 \\ 2 \end{bmatrix}

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 x\mathbf{x} 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 jj as row jj of a matrix turns the whole layer into one line:

y=Wx+b\mathbf{y} = \mathbf{W}\mathbf{x} + \mathbf{b}

The vector b\mathbf{b} holds one bias per output, a number added on regardless of the input. With b=[0.5,−1]\mathbf{b} = [0.5, -1] our example gives y=[4.5,1]\mathbf{y} = [4.5, 1]. 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.

x₁ x₂ x₃ y₁ y₂ 3 inputs 2 outputs 6 connections = 6 weights 1, 0, 2 −1, 3, 1 same 1 0 2 −1 3 1 weight matrix W (2 × 3) row j = the weights into output j y = Wx + b one layer = one matrix multiply
Fig. 2 A layer with 3 inputs and 2 outputs. Each of the 6 connections has a weight (line thickness shows its size; the dashed line is a weight of zero). Writing the weights into output 1 as the first row and the weights into output 2 as the second row gives the 2 × 3 weight matrix W, and the whole layer becomes y = Wx + b.

Real layers are big. One feed-forward layer of GPT-3 has a weight matrix of shape 49,152×12,28849{,}152 \times 12{,}288, 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 (i,j)(i, j) of the result is the dot product of row ii of the first matrix with column jj of the second.

[1234][5678]=[1⋅5+2⋅71⋅6+2⋅83⋅5+4⋅73⋅6+4⋅8]=[19224350]\begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} \begin{bmatrix} 5 & 6 \\ 7 & 8 \end{bmatrix} = \begin{bmatrix} 1 \cdot 5 + 2 \cdot 7 & 1 \cdot 6 + 2 \cdot 8 \\ 3 \cdot 5 + 4 \cdot 7 & 3 \cdot 6 + 4 \cdot 8 \end{bmatrix} = \begin{bmatrix} 19 & 22 \\ 43 & 50 \end{bmatrix}

The shape rule is the single most useful thing to memorise:

(m×n)⋅(n×p)→(m×p)(m \times n) \cdot (n \times p) \rightarrow (m \times p)

The inner sizes (nn and nn) must match, and they disappear. The outer sizes give the result. A (64×768)(64 \times 768) matrix times a (768×3072)(768 \times 3072) matrix gives (64×3072)(64 \times 3072). A (64×768)(64 \times 768) times a (512×768)(512 \times 768) is an error.

Three properties to know:

  • Order matters. In general AB≠BA\mathbf{A}\mathbf{B} \neq \mathbf{B}\mathbf{A}. Swap the two matrices above and you get [23343146]\begin{bmatrix} 23 & 34 \\ 31 & 46 \end{bmatrix}. As transformations, "rotate then stretch" differs from "stretch then rotate".
  • Grouping does not matter. (AB)C=A(BC)(\mathbf{A}\mathbf{B})\mathbf{C} = \mathbf{A}(\mathbf{B}\mathbf{C}). You can combine a chain of transformations into one matrix in advance.
  • Cost. Multiplying an m×nm \times n by an n×pn \times p matrix takes m×n×pm \times n \times p 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 BB input vectors as the rows of a matrix X\mathbf{X} of shape B×3B \times 3. Then the whole layer, for all examples at once, is

Y=XW⊤+b\mathbf{Y} = \mathbf{X}\mathbf{W}^\top + \mathbf{b}

with shape (B×3)⋅(3×2)→(B×2)(B \times 3) \cdot (3 \times 2) \rightarrow (B \times 2): one row of outputs per example. The ⊤\top is the transpose, explained next. One big matrix multiplication is far faster on a GPU than BB small ones, which is why training uses mini-batches.

Transpose

The transpose A⊤\mathbf{A}^\top flips a matrix over its diagonal: rows become columns.

[1234]⊤=[1324]\begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}^\top = \begin{bmatrix} 1 & 3 \\ 2 & 4 \end{bmatrix}

An m×nm \times n matrix becomes n×mn \times m. Transposes appear all the time to make shapes line up, as in XW⊤\mathbf{X}\mathbf{W}^\top above. The dot product of two column vectors can also be written a⊤b\mathbf{a}^\top \mathbf{b}: a (1×n)(1 \times n) times an (n×1)(n \times 1) gives a 1×11 \times 1 result, a single number.

Identity and inverse

The identity matrix I\mathbf{I} has 1s on the diagonal and 0s elsewhere:

I=[1001]\mathbf{I} = \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}

It is the "do nothing" transformation: Ix=x\mathbf{I}\mathbf{x} = \mathbf{x} for every x\mathbf{x}, just as multiplying a number by 1 leaves it alone.

Some matrices can be undone. The matrix inverse A−1\mathbf{A}^{-1} is the transformation that reverses A\mathbf{A}, so A−1A=I\mathbf{A}^{-1}\mathbf{A} = \mathbf{I}. 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 dimension means the inner sizes differ. Print .shape of both sides and apply the shape rule. Usually one side needs a transpose.
  • * instead of @. A * B multiplies 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. AB\mathbf{A}\mathbf{B} and BA\mathbf{B}\mathbf{A} usually differ, and one of them may not even exist.
  • Computing inverses. np.linalg.inv(A) @ b is slower and less accurate than np.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 @ W and x @ W.T both 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, QK⊤\mathbf{Q}\mathbf{K}^\top.
  • 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

  1. By hand, compute [0−110][31]\begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix} \begin{bmatrix} 3 \\ 1 \end{bmatrix}. Draw the input and the output arrows. What did the matrix do?
  2. You have a batch of 32 images, each flattened to 784 numbers, and a layer with 128 outputs. What are the shapes of X\mathbf{X}, W\mathbf{W} (PyTorch convention) and the output? How many weights does the layer have?
  3. Check in NumPy that (AB)⊤=B⊤A⊤(\mathbf{A}\mathbf{B})^\top = \mathbf{B}^\top \mathbf{A}^\top for two random matrices of shapes 2×32 \times 3 and 3×43 \times 4.

Hint for 1: the result is [−1,3][-1, 3]. Look at the angle between the two arrows. The columns of the matrix tell you where e1\mathbf{e}_1 and e2\mathbf{e}_2 go.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You multiply a matrix of shape (64 × 768) by one of shape (768 × 3072). What is the shape of the result?

  2. Your from-scratch layer uses A * B where you meant matrix multiplication, with A and B both 3 × 3. What happens?

  3. Why does a real neural network put a non-linear activation between its matrix multiplications?

  4. A layer takes 784 inputs and produces 128 outputs. In PyTorch's nn.Linear convention, what is the shape of the weight matrix?

  5. You double every size of two matrices you multiply (m, n and p). Roughly how much more work does the multiplication take?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Video

Essence of Linear Algebra

3Blue1Brown · Beginner · Free

A visual intuition for vectors, matrices, determinants and eigenvectors. You will see the ideas, not just the rules.

Course

Linear Algebra

Khan Academy · Beginner · Free

Patient video lessons with exercises on vectors, matrices and transformations.

Interactive

Immersive Linear Algebra

J. Ström, K. Åström & T. Akenine-Möller · Beginner · Free

A free linear algebra book whose figures you can drag and rotate. Excellent for seeing vectors, dot products and matrices as geometry.

Course

MIT 18.06: Linear Algebra

Gilbert Strang (MIT OpenCourseWare) · 2010 · Intermediate · Free

The classic university linear algebra course, with full video lectures, notes and problem sets. Strang explains matrices as things that act on vectors.

Book

Mathematics for Machine Learning

Deisenroth, Faisal & Ong · 2020 · Intermediate · Free

The linear algebra, calculus, probability and optimisation that ML uses, in one free book.

Article

Linear Algebra Review and Reference

Zico Kolter (Stanford CS229) · Intermediate · Free

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.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/math/matrices.md