Mathematical Foundations

II.10 · Linear Algebra

Apply A, then B: the combined matrix is BA.

Keep the intermediate vector visible, compare BA with AB, follow rectangular dimensions, and compose affine maps without confusing their translations.

Apply A, then B; keep the middle state visible

A acts first and B second, so the combined matrix is BA, not AB.

matrix A
2×2 [1, 1; 0, 1]
matrix B (applied second)
2×2 [1, 0; 1, 1]
input vector
(2, 1)
intermediate state after A
(3, 1)
combined linear transformation
2×2 [1, 1; 1, 2]
final state after B
(3, 4)
opposite order for comparison
2×2 [2, 1; 1, 1]

Exact expressions use =. Rounded computations use ≈. Every view uses this same state.

A acts first and B second, so the combined matrix is BA, not AB.

B(Ax)=(BA)x=[34]B(A\mathbf x)=(BA)\mathbf x=\begin{bmatrix}3\\4\end{bmatrix}
BA=[1112]≠AB=[2111]BA=\begin{bmatrix}1&1\\1&2\end{bmatrix}\ne AB=\begin{bmatrix}2&1\\1&1\end{bmatrix}

from −4 to 4, up to 2 decimal places

from −4 to 4, up to 2 decimal places

from −4 to 4, up to 2 decimal places

from −4 to 4, up to 2 decimal places

from −4 to 4, up to 2 decimal places

from −4 to 4, up to 2 decimal places

from −4 to 4, up to 2 decimal places

from −4 to 4, up to 2 decimal places

from −4 to 4, up to 2 decimal places

from −4 to 4, up to 2 decimal places

The first polygon and arrow show A’s intermediate state; the second shows B after A. Compare BA with AB, then inspect rectangular and affine compositions.

Move x\mathbf x and track x→Ax→B(Ax)\mathbf x\to A\mathbf x\to B(A\mathbf x). Before choosing Swap order, predict whether the final point stays fixed. Use 2→3→2 to read the dimensions without relying on a plane picture. Then choose Affine bridge and isolate the combined translation.

Intuition: replace a pipeline without erasing its order

Two transformations form a pipeline. AA consumes the original input; BB consumes the output of AA. A matrix product packages that pipeline as one linear map, but the visible intermediate state explains what the package means.

Function notation already fixes the order:

x⟼Ax⟼B(Ax).\mathbf x\longmapsto A\mathbf x\longmapsto B(A\mathbf x).

The later operation appears on the left, so the combined matrix is BABA.

Definition

If AA is m×nm\times n and BB is p×mp\times m, their product BABA is the p×np\times n matrix whose entries are

(BA)ij=∑k=1mbikakj.(BA)_{ij}=\sum_{k=1}^{m}b_{ik}a_{kj}.

Its jjth column is BB applied to the jjth column of AA. Therefore BABA records where the complete composition sends every input basis vector.

Mechanics: follow dimensions and the middle space

The dimension chain is

Rn→ARm→BRp,(p×m)(m×n)=p×n.\mathbb R^n\xrightarrow{A}\mathbb R^m\xrightarrow{B}\mathbb R^p, \qquad (p\times m)(m\times n)=p\times n.

The shared mm is the intermediate space. A 3×23\times2 map followed by a 2×32\times3 map produces a 2×22\times2 combined map. Reversing the factors describes a different route and yields a 3×33\times3 matrix.

Derivation: associativity connects the pipeline

Expand one output component:

(B(Ax))i=∑kbik(Ax)k=∑kbik∑jakjxj=∑j(∑kbikakj)xj=((BA)x)i.\begin{aligned} \bigl(B(A\mathbf x)\bigr)_i &=\sum_k b_{ik}(A\mathbf x)_k\\ &=\sum_k b_{ik}\sum_j a_{kj}x_j\\ &=\sum_j\left(\sum_k b_{ik}a_{kj}\right)x_j\\ &=((BA)\mathbf x)_i. \end{aligned}

This proves B(Ax)=(BA)xB(A\mathbf x)=(BA)\mathbf x. Regrouping is valid, so matrix multiplication is associative. Swapping factors is a different operation, so multiplication is generally not commutative.

Noncommutativity in geometry

Consider a horizontal shear and a quarter-turn. Shearing a shape and then turning it does not usually place its slanted edge where turning first and shearing does. The stage draws both BABA and ABAB exactly; unequal results are structural, not a rendering artifact.

Some particular matrices do commute, including every matrix with the identity. One agreeing example does not establish a general commutative law.

Affine composition

Suppose the first map is x↦Ax+b\mathbf x\mapsto A\mathbf x+\mathbf b and the second is y↦By+c\mathbf y\mapsto B\mathbf y+\mathbf c. Substitution gives

B(Ax+b)+c=(BA)x+(Bb+c).B(A\mathbf x+\mathbf b)+\mathbf c =(BA)\mathbf x+(B\mathbf b+\mathbf c).

The linear parts multiply in the same order. The first translation is itself transformed by BB before the second translation is added. Simply adding b+c\mathbf b+\mathbf c is generally wrong.

Worked examples

For

A=[1101],B=[1011],x=[21].\begin{aligned} A&=\begin{bmatrix}1&1\\0&1\end{bmatrix}, &B&=\begin{bmatrix}1&0\\1&1\end{bmatrix},\\ \mathbf x&=\begin{bmatrix}2\\1\end{bmatrix}. \end{aligned}

we obtain Ax=(3,1)A\mathbf x=(3,1), then B(Ax)=(3,4)B(A\mathbf x)=(3,4). Direct multiplication gives BA=[1112]BA=\begin{bmatrix}1&1\\1&2\end{bmatrix}, and (BA)x=(3,4)(BA)\mathbf x=(3,4).

Inspect the worked calculation

Apply A to x and keep Ax visible.

B(Ax)=(BA)x=[34]B(A\mathbf x)=(BA)\mathbf x=\begin{bmatrix}3\\4\end{bmatrix}
matrix A
2×2 [1, 1; 0, 1]
matrix B (applied second)
2×2 [1, 0; 1, 1]
input vector
(2, 1)
intermediate state after A
(3, 1)
combined linear transformation
2×2 [1, 1; 1, 2]
final state after B
(3, 4)
opposite order for comparison
2×2 [2, 1; 1, 1]
Keep Ax visible, then replace the two exact steps by BA without changing the result.

The opposite product is AB=[2111]AB=\begin{bmatrix}2&1\\1&1\end{bmatrix}, which is different. Both are valid products; they encode different pipelines.

Executable reference code

The Python reference validates rectangular shapes and computes both a composition and its application. The NumPy file checks sequential and combined evaluations, demonstrates noncommutativity, and keeps affine translation separate.

code/python/matrix_composition.py
from fractions import Fraction as F


def matvec(a, x):
    return tuple(sum((entry * value for entry, value in zip(row, x)), F(0)) for row in a)


def matmul(left, right):
    if len(left[0]) != len(right):
        raise ValueError("inner dimensions must match")
    columns = tuple(zip(*right))
    return tuple(tuple(sum((x * y for x, y in zip(row, column)), F(0)) for column in columns) for row in left)


A = ((F(1), F(1)), (F(0), F(1)))
B = ((F(1), F(0)), (F(1), F(1)))
x = (F(2), F(1))
BA = matmul(B, A)
assert matvec(B, matvec(A, x)) == matvec(BA, x) == (3, 4)
assert BA != matmul(A, B)

b, c = (F(1), F(-1)), (F(0), F(2))
combined_translation = tuple(u + v for u, v in zip(matvec(B, b), c))
assert combined_translation == (1, 2)
code/python/matrix_composition_numpy.py
import numpy as np

A = np.array([[1.0, 1.0], [0.0, 1.0]])
B = np.array([[1.0, 0.0], [1.0, 1.0]])
x = np.array([2.0, 1.0])
b, c = np.array([1.0, -1.0]), np.array([0.0, 2.0])

np.testing.assert_allclose(B @ (A @ x), (B @ A) @ x)
assert not np.array_equal(B @ A, A @ B)
np.testing.assert_allclose(B @ (A @ x + b) + c, (B @ A) @ x + (B @ b + c))

Explore

Set AA to the identity and explain why both orders agree. Set B=AB=A and compare A2A^2 with two visible applications. In the rectangular preset, name the input, middle, and output dimensions. In the affine preset, set c=0\mathbf c=\mathbf0 and change only b\mathbf b; explain why the final shift follows BbB\mathbf b.

Common mistakes

Do not read BABA left to right as a timeline. Do not multiply entries position by position. Do not assume AB=BAAB=BA, and do not infer that both orders are even defined for rectangular matrices. For affine maps, do not fold translations into the linear product or add them without transforming the earlier shift.

Numerical considerations

Exact rational examples make sequential and combined outputs identical. Floating-point software may produce slightly different last bits because the two evaluation orders group sums differently. In deep pipelines, shapes and operation order should be asserted explicitly, while performance libraries choose stable kernels appropriate to the hardware.

Engineering and ML connections

Layers, coordinate changes, camera transforms, and data-processing stages compose in this same order. Several linear layers with no intervening nonlinearity collapse mathematically to one matrix; nonlinear activations prevent that collapse and give deep networks more expressive structure. Bias vectors follow the affine composition law above.

Exercises

calculation

Compose two maps

A = [[1, 1], [0, 1]] acts first and B = [[1, 0], [1, 1]] second. Give BA by rows.

prediction

Keep the order straight

A acts first and B acts second. Which single matrix has the same effect?

Choose one answer

calculation

Keep the middle state

A sends x = (1, 2) to (3, 2). B sends (u, v) to (u, u + v). Compute B(Ax).

prediction

Follow dimensions

A is 3×2 and B is 2×3. What is the shape of BA?

Choose one answer

calculation

Compose translations

B = [[2, 0], [0, 1]], first translation b = (1, −1), and second translation c = (0, 3). Compute Bb + c.

Summary and checkpoints

Matrix multiplication represents composition: AA first and BB second become BABA. Check that you can follow the intermediate space, compute a product by row–column pairings, explain noncommutativity, and compose affine translations as Bb+cB\mathbf b+\mathbf c. Next we study transformations that preserve Euclidean geometry.

The map of the book

97 of 97 chapters written · eight Parts

demo Foundation demo Try the live vector example Open as a page

Part I

Mathematical Language

The notation and mental objects everything else uses.

9 of 9 chapters written

  1. I.1 Scalars, quantities, units, powers and roots available
  2. I.2 Coordinates and points available
  3. I.3 Vectors: components, magnitude, and direction reference chapter available
  4. I.4 Algebraic expressions, equations and inequalities available
  5. I.5 Functions as input → transformation → output available
  6. I.6 Essential function families available
  7. I.7 Sets, intervals, and relations available
  8. I.8 Indexed quantities and summation available
  9. I.9 The notation map for ML available

Part II

Linear Algebra

Matrices as transformations: the strongest foundation in the book.

19 of 19 chapters written

  1. II.1 Vector addition and subtraction available
  2. II.2 Scalar multiplication and vector scaling available
  3. II.3 Norms, magnitude, and normalization available
  4. II.4 Dot product, angle, and orthogonality available
  5. II.5 Projection and distance to a direction available
  6. II.6 Linear combinations and span available
  7. II.7 Linear independence, basis, and coordinates available
  8. II.8 Matrices as linear transformations available
  9. II.9 Matrix × vector available
  10. II.10 Matrix × matrix as composition available
  11. II.11 Transpose and orthogonality available
  12. II.12 Determinant: orientation and area/volume scaling available
  13. II.13 Linear systems as intersecting constraints available
  14. II.14 Gaussian elimination and row operations available
  15. II.15 Rank and invertibility available
  16. II.16 Inverse matrices available
  17. II.17 Eigenvalues and eigenvectors available
  18. II.18 Orthogonal bases and least-squares geometry available
  19. II.19 Singular Value Decomposition available

Part III

Calculus

Change, local approximation, and sensitivity made visible.

15 of 15 chapters written

  1. III.1 Limits through approach available
  2. III.2 Continuity and local behavior available
  3. III.3 Derivative as secant → tangent available
  4. III.4 Derivative as rate of change and local linear model available
  5. III.5 Derivative rules available
  6. III.6 Chain rule available
  7. III.7 Multivariable functions and partial derivatives available
  8. III.8 Gradient and directional derivatives available
  9. III.9 Jacobian available
  10. III.10 Computational graphs and automatic differentiation available
  11. III.11 Hessian and curvature available
  12. III.12 Integrals as accumulation available
  13. III.13 Fundamental derivative/integral connection available
  14. III.14 Numerical differentiation available
  15. III.15 Numerical integration available

Part IV

Probability

Uncertainty through sample spaces, evidence, and repetition.

16 of 16 chapters written

  1. IV.1 Random experiments, outcomes, and sample spaces available
  2. IV.2 Events and probability mass available
  3. IV.3 Counting and finite probability where needed available
  4. IV.4 Conditional probability as restricted sample space available
  5. IV.5 Independence available
  6. IV.6 Bayes' theorem as probability-mass update available
  7. IV.7 Random variables available
  8. IV.8 PMF, PDF, and CDF available
  9. IV.9 Bernoulli and Binomial distributions available
  10. IV.10 Uniform and Gaussian distributions available
  11. IV.11 Expectation available
  12. IV.12 Variance and standard deviation available
  13. IV.13 Joint, marginal, and conditional distributions available
  14. IV.14 Covariance and correlation available
  15. IV.15 Law of Large Numbers available
  16. IV.16 Central Limit Theorem available

Part V

Statistics

From observed data to estimates, intervals, and likelihood.

10 of 10 chapters written

  1. V.1 Data summaries: mean, median, mode available
  2. V.2 Spread: variance, standard deviation, robust interpretation available
  3. V.3 Population, sample, and sampling variability available
  4. V.4 Estimators and estimation available
  5. V.5 Confidence intervals through repeated sampling available
  6. V.6 Covariance matrices and multivariate spread available
  7. V.7 Regression fundamentals available
  8. V.8 Likelihood available
  9. V.9 Maximum Likelihood Estimation available
  10. V.10 Maximum A Posteriori estimation available

Part VI

Optimization

Learning as repeated parameter updates governed by an objective.

10 of 10 chapters written

  1. VI.1 Objective functions and optimization landscapes available
  2. VI.2 Local vs global optima and stationary points available
  3. VI.3 Convexity available
  4. VI.4 Gradient descent flagship chapter available
  5. VI.5 Learning rate and convergence behavior available
  6. VI.6 Momentum available
  7. VI.7 Stochastic and mini-batch gradient descent available
  8. VI.8 Adam intuition available
  9. VI.9 Constraints and projected/penalized intuition available
  10. VI.10 Numerical stopping and optimization diagnostics available

Part VII

Information Theory

Logarithms, entropy, and the loss behind token prediction.

8 of 8 chapters written

  1. VII.1 Logarithms and log probabilities in computation available
  2. VII.2 Self-information available
  3. VII.3 Entropy available
  4. VII.4 Cross entropy and negative log-likelihood available
  5. VII.5 KL divergence available
  6. VII.6 Logits and softmax available
  7. VII.7 Numerical stability: log-sum-exp and stable softmax available
  8. VII.8 From token logits to language-model loss available

Part VIII

Numerical Computing

Why equivalent expressions behave differently on real machines.

10 of 10 chapters written

  1. VIII.1 Floating-point representation available
  2. VIII.2 Rounding and representation error available
  3. VIII.3 Error propagation and conditioning available
  4. VIII.4 Catastrophic cancellation available
  5. VIII.5 Overflow and underflow available
  6. VIII.6 Stable algorithms available
  7. VIII.7 Numerical linear algebra realities available
  8. VIII.8 Sparse matrices and sparse structure available
  9. VIII.9 Vectorized computation available
  10. VIII.10 Reproducibility, random seeds, and nondeterminism available