Skip to content
AI360XpertBeta

Matrix Operations

Matrices add entry by entry, multiply row by column with inner sizes that must match, and transpose flips rows into columns.

Two 2 by 2 matrices multiply row by column into 19, 22, 43 and 50, and only matching inner sizes let the product exist.
Two 2 by 2 matrices multiply row by column into 19, 22, 43 and 50, and only matching inner sizes let the product exist.

Why Does This Exist?

Every dense layer of a neural network is a matrix operation. A batch of inputs multiplies a weight matrix, adds a bias, and moves on. Centering data subtracts means entry by entry, attention scores a matrix against its transpose, and backpropagation flows through the same three verbs in reverse. If addition, multiplication, and transpose feel shaky, nothing built on top of them can feel solid.

Vectors, matrices, and tensors introduces what these objects are. This page is the verbs: the three operations, their shape rules, and the order trap. The dedicated matrix multiplication page goes deeper on the geometry of that one operation; here multiplication sits alongside its two siblings so the three can be compared side by side.

The one idea you need first

A shape like 2×32 \times 3 reads rows first: 2 rows, 3 columns. Entry aija_{ij} sits in row ii, column jj. In plain words, the first number says how tall the table is and the second says how wide. Nearly every error in this subject is a shape error, so read both shapes before computing anything.

Think of It Like This

Recipes scaled across kitchens

Think of a matrix as a recipe card. Rows are dishes, columns are ingredients. Adding two cards blends two menus dish by dish: lasagna with lasagna, sauce with sauce. Multiplying is fulfilling orders: each row of the first card, one dish and everything it needs, meets each column of the second card, one supplier and everything they stock, and each meeting produces one total cost. Transposing rewrites the card sideways, ingredients as rows, so tomorrow's computation reads naturally.

Where it stops: real matrices multiply numbers, not intentions, and the row meets column rule has no flexibility. A dish listing 3 ingredient amounts can only meet a supplier listing exactly 3 prices. That rigidity is the inner size rule with an apron on.

How It Actually Works

Addition works entry by entry and needs identical shapes. In plain words, each position combines only with the same position in the other matrix:

[1234]+[5678]=[681012]\begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} + \begin{bmatrix} 5 & 6 \\ 7 & 8 \end{bmatrix} = \begin{bmatrix} 6 & 8 \\ 10 & 12 \end{bmatrix}

A 2×22 \times 2 plus a 2×32 \times 3 is undefined. Libraries bend this rule with broadcasting, but the mathematics does not: same shape or no sum.

Multiplication works row by column, and the inner sizes must match. For C=ABC = AB, entry cijc_{ij} is row ii of AA dotted with column jj of BB, using the dot product. An (m×n)(m \times n) times an (n×p)(n \times p) gives an (m×p)(m \times p): the inner nn values must agree and the outer sizes survive into the answer.

Worked example

Take these two matrices, both 2×22 \times 2, so the product is 2×22 \times 2:

A=[1234],B=[5678]A = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}, \qquad B = \begin{bmatrix} 5 & 6 \\ 7 & 8 \end{bmatrix}

Compute each entry as one row meeting one column:

  • c11=1×5+2×7=5+14=19c_{11} = 1 \times 5 + 2 \times 7 = 5 + 14 = 19
  • c12=1×6+2×8=6+16=22c_{12} = 1 \times 6 + 2 \times 8 = 6 + 16 = 22
  • c21=3×5+4×7=15+28=43c_{21} = 3 \times 5 + 4 \times 7 = 15 + 28 = 43
  • c22=3×6+4×8=18+32=50c_{22} = 3 \times 6 + 4 \times 8 = 18 + 32 = 50

So AB=[19224350]AB = \begin{bmatrix} 19 & 22 \\ 43 & 50 \end{bmatrix}, exactly the numbers drawn in the diagram above, where the highlighted row of AA meets the highlighted column of BB to make the highlighted 1919. Reversing the order gives BA=[23343146]BA = \begin{bmatrix} 23 & 34 \\ 31 & 46 \end{bmatrix}: check 1×5+6×3=231 \times 5 + 6 \times 3 = 23 for the top left, and the rest follow the same way. Both products exist and they disagree everywhere, which proves the headline warning that AB≠BAAB \neq BA in general.

Transpose flips across the diagonal. Rows become columns, so an (m×n)(m \times n) becomes an (n×m)(n \times m), and entry (i,j)(i, j) moves to (j,i)(j, i):

AT=[1324]A^T = \begin{bmatrix} 1 & 3 \\ 2 & 4 \end{bmatrix}

Transposing twice returns the original, so (AT)T=A(A^T)^T = A. Sizes in this subject are measured with norms, which is where the length of a row or column gets its number.

Code

The point of this snippet is the check, not the formula: multiply the worked matrices and confirm every entry, including the reversed order, so a sign or order slip cannot hide.

import numpy as np

def mat_product(a: np.ndarray, b: np.ndarray) -> np.ndarray:    # One call, but the shapes must already agree on the inner size.    return a @ b

a = np.array([[1, 2], [3, 4]])b = np.array([[5, 6], [7, 8]])print(mat_product(a, b))  # -> [[19 22] [43 50]]print(mat_product(b, a))  # -> [[23 34] [31 46]]

Both outputs match the hand computation, including the reversed product that proves order matters.

Watch Out For

Multiplying matrices whose inner sizes disagree

The symptom is a shape error late at night: a 4×34 \times 3 weight meeting a 4×14 \times 1 input and refusing to multiply. The fix is the outer inner chant. Write both shapes down, check the two middle numbers match, and read the answer shape off the two outer numbers. Nine times out of ten the repair is a missing transpose on one side, which is exactly why transpose exists as an operation rather than a convenience.

Assuming AB equals BA

Scalar habits die hard, and matrix multiplication is not commutative. The symptom is a silently wrong result, because BABA often has a valid shape and computes without complaint, as the worked example shows with two fully valid but different answers. Rotations, projections, and gradients all depend on the order. When porting a formula, preserve the order exactly; when debugging, swap the suspects deliberately and compare against the expected 1919, 2222, 4343, 5050.

The Quick Version

  • Addition is entry by entry and needs identical shapes, or the sum is undefined.
  • Multiplication is row by column: an (m×n)(m \times n) times an (n×p)(n \times p) gives an (m×p)(m \times p).
  • The worked product here is [19224350]\begin{bmatrix} 19 & 22 \\ 43 & 50 \end{bmatrix}, from 1×5+2×7=191 \times 5 + 2 \times 7 = 19 and three siblings.
  • Transpose moves entry (i,j)(i, j) to (j,i)(j, i) and flips an (m×n)(m \times n) into an (n×m)(n \times m).
  • AB≠BAAB \neq BA in general: the reversed example gives [23343146]\begin{bmatrix} 23 & 34 \\ 31 & 46 \end{bmatrix}.
  • When shapes refuse to multiply, check the inner sizes first, then suspect a missing transpose.