Chapter 3 · PDF Pages 75-116

Matrices: operations, norms, and geometry

The whole book is also in the PDF.

This chapter moves from one-dimensional vectors to two-dimensional matrices, the fundamental structures for representing datasets, transformations, and the very architecture of neural networks. We begin by defining matrices and their basic properties, establishing notational foundations and introducing special matrices that serve as building blocks in AI algorithms. We then conduct an exploration of matrix operations –addition, multiplication, and inner products– with a persistent focus on their computational complexity using Big-O notation. The chapter delves into the generalization of geometric concepts from vectors to matrices, defining matrix norms, distances, and the inequalities that govern them. Through this process, we build not just an algebraic understanding, but a geometric intuition for how matrices operate in high-dimensional spaces.

Keywords. Matrices | Matrix Operations | Computational Complexity | Matrix-Vector Multiplication | Matrix-Matrix Multiplication | Matrix Norms | Frobenius Norm

3.1 The Matrix

If vectors are the atoms of AI, representing single data points or feature sets, then matrices are the molecules and materials built from them. A matrix arranges vectors into a structured, two-dimensional grid, providing a natural way to represent entire collections of data, the relationships between different data points, and the linear transformations that are central to AI algorithms.

3.1.1 Definition and Notation

A matrix is a rectangular array of numbers, arranged in rows and columns. A matrix with \(m\) rows and \(p\) columns is called an \(m \times p\) matrix and is an element of the vector space \(\mathbb{R}^{m \times p}\). We denote a matrix with a bold uppercase letter:

\[ \mathbf{A} = \begin{bmatrix} A_{11} & A_{12} & \cdots & A_{1p} \\ A_{21} & A_{22} & \cdots & A_{2p} \\ \vdots & \vdots & \ddots & \vdots \\ A_{m1} & A_{m2} & \cdots & A_{mp} \end{bmatrix} \in \mathbb{R}^{m \times p}. \]

The scalar entry in the \(i\)-th row and \(j\)-th column of \(\mathbf{A}\) is denoted by \(A_{ij}\) or \((\mathbf{A})_{ij}\). It is often useful to view an \(m \times p\) matrix as a collection of \(p\) column vectors, each belonging to \(\mathbb{R}^m\), or as a collection of \(m\) row vectors, each belonging to \(\mathbb{R}^p\). E.g.,

\[ \mathbf{A} = \begin{bmatrix} | & | & & | \\ \mathbf{a}_1 & \mathbf{a}_2 & \cdots & \mathbf{a}_p \\ | & | & & | \end{bmatrix}. \]

Example 3.1. The matrix

\[ \begin{aligned} \mathbf{B} = \begin{bmatrix} 1.3 & 4.0 & -0.1 \\ 0.0 & 1.0 & -2.3 \end{bmatrix} \end{aligned} \]

is a \(2 \times 3\) matrix, so \(\mathbf{B} \in \mathbb{R}^{2 \times 3}\). Its dimensions are \(m=2\) rows and \(p=3\) columns. The element \(B_{23}\) is \(-2.3\).

3.1.2 Examples

The Data Matrix: The Foundation of Supervised Learning. In virtually any learning task, from simple linear regression to training complex classifiers (more about these, in the ML/AI courses to follow), the entire dataset is often organized into a data matrix, often denoted as \(\mathbf{A}\) or \(\mathbf{X}\).

In this matrix, each row represents a single data point or observation (e.g., a patient in a medical study, a house for sale, a customer). Each column corresponds to a specific feature or attribute of that observation (e.g., a patient’s age, the square footage of a house, a customer’s total spending). Therefore, the element \(A_{ij}\) represents the value of the \(j\)-th feature for the \(i\)-th data point.

This structure is fundamental because it allows us to perform operations on the entire dataset simultaneously using efficient, vectorized computations. For example, in linear systems of equations, if we have a vector of model weights \(\mathbf{w}\), the matrix-vector product \(\mathbf{y}_{\text{pred}} = \mathbf{A}\mathbf{w}\) computes the predicted output for every single data point in one shot.

The Image Matrix: The Canvas for Computer Vision. A digital image is inherently a matrix, making this one of the most direct and intuitive applications. For a grayscale image, the data is stored in a single matrix where each element \(A_{ij}\) corresponds to the intensity (brightness) of the pixel at the spatial coordinate \((i, j)\).1

This representation is powerful because matrix operations correspond directly to image processing tasks. For instance, in Convolutional Neural Networks (CNNs), the core operation is convolution, which involves sliding a small matrix called a kernel (or filter) across the image matrix.

The Adjacency Matrix: Representing Relationships in Networks. Graphs are used to model complex relationships, such as social networks, molecular structures, or transportation systems. To process this data with mathematical algorithms, we convert the graph into an adjacency matrix. For a graph with \(N\) nodes, the adjacency matrix \(\mathbf{A}\) is an \(N \times N\) matrix. The entry \(A_{ij}\) is typically 1 if there is a connection (an edge) from node \(i\) to node \(j\), and 0 otherwise. The matrix is symmetric if the connections are bidirectional (e.g., Facebook friendships).

The adjacency matrix translates the abstract structure of a network into a numerical object that optimization algorithms can manipulate. A key operation is matrix multiplication (we will see this later on in this chapter). For example, the matrix product \(\mathbf{A}^2 = \mathbf{A}\mathbf{A}\) has a fascinating property: the entry \((\mathbf{A}^2)_{ij}\) counts the number of paths of length two between node \(i\) and node \(j\). This concept is the cornerstone of Graph Neural Networks (GNNs).

The Weight Matrix: The “Brain” of a Neural Network. In a deep neural network, the knowledge learned by the model is stored entirely within a set of weight matrices. A neural network consists of layers of “neurons.” A weight matrix \(\mathbf{W}\) connects one layer to the next. If a layer has \(n\) neurons and the next layer has \(m\) neurons, the weight matrix \(\mathbf{W}\) connecting them will have dimensions \(m \times n\). The element \(W_{ij}\) represents the strength of the connection from the \(j\)-th neuron in the first layer to the \(i\)-th neuron in the second layer.

The fundamental operation of a neural network, called forward propagation, is essentially a sequence of matrix-vector multiplications. If the activations of one layer are represented by a vector \(\mathbf{x}\), the input to the next layer is computed as \(\mathbf{z} = \mathbf{W}\mathbf{x}\) (before a non-linear activation function is applied). This operation transforms the representation of the data from one layer to the next. The entire process of “training” a neural network is a massive optimization problem: finding the numerical values for all the weight matrices in the network that minimize a final loss function, which measures the difference between the network’s predictions and the true labels.

3.1.3 Special Matrices

Certain matrices with specific structures are fundamental tools in linear algebra and appear frequently in AI contexts.

  • Zero Matrix (\(\mathbf{0}\)): A matrix of any dimension with all its elements equal to zero. It is the additive identity in matrix addition: i.e., \(\mathbf{A} + \mathbf{0} = \mathbf{A}\), where \(\mathbf{A}\) and \(\mathbf{0}\) have the same dimensions.
  • Ones Matrix (\(\mathbf{1}\)): A matrix of any dimension with all its elements equal to one. It is useful for aggregation operations.
  • Identity Matrix (\(\mathbf{I}\)): A square matrix (\(m=p\)) with ones on its main diagonal (where \(i=j\)) and zeros everywhere else. \[ \mathbf{I}_3 = \begin{bmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{bmatrix}. \]

    The identity matrix is the multiplicative identity; it is the matrix equivalent of the number 1 for scalars. I.e., \(\mathbf{A} \cdot \mathbf{I} = \mathbf{A}\).

  • Sparse Matrix: A matrix where the vast majority of its elements are zero. Representing large sparse matrices efficiently by only storing the non-zero elements is a key technique in computational science and in models dealing with high-dimensional, sparse data like text (e.g., document-term matrices). For instance, sparsity is a desirable property of AI models, where most of the model’s parameters are zero, as it leads to faster performance (think of getting an answer from ChatGPT faster) and more efficient usage of resources (think of making ChatGPT fit and run in a small device).
  • Symmetric Matrix: A square matrix \(\mathbf{A}\) is symmetric if the element in the \(i\)-th row and \(j\)-th column is equal to the element in the \(j\)-th row and \(i\)-th column for all pairs of indices: \(A_{ij} = A_{ji}\). The matrix is visually symmetric across its main diagonal (from top-left to bottom-right).

3.1.4 Storage Complexity

A standard, or dense, \(m \times p\) matrix is stored in computer memory as a contiguous block of \(m \times p\) numbers. If each number is a standard 64-bit float, this requires \(8mp\) bytes of memory. The storage cost is \(O(mp)\). For a sparse matrix, however, we can do much better. Instead of storing all \(mp\) entries, we only store the non-zero values along with their row and column indices. If a matrix has \(\text{nnz}(\mathbf{A})\) non-zero entries, the storage cost is closer to \(O(\text{nnz}(\mathbf{A}))\), which can be a dramatic saving when \(\text{nnz}(\mathbf{A}) \ll mp\).

3.1.5 Fundamental Matrix Operations and Their Complexity

Matrix Addition and Subtraction. Two matrices of the same dimensions can be added or subtracted. The operation is performed element-wise. Given \(\mathbf{A}, \mathbf{B} \in \mathbb{R}^{m \times p}\), their sum \(\mathbf{C} = \mathbf{A} + \mathbf{B}\) is defined by \(C_{ij} = A_{ij} + B_{ij}\).

  • Properties: Matrix addition is commutative (\(\mathbf{A}+\mathbf{B} = \mathbf{B}+\mathbf{A}\)) and associative (\((\mathbf{A}+\mathbf{B}) + \mathbf{C} = \mathbf{A} + (\mathbf{B}+\mathbf{C})\)).
  • Complexity: The operation of adding/subtracting two matrices of dimensions \(m \times p\) requires \(mp\) additions/subtractions. The complexity is therefore \(O(mp)\).

Example 3.2 (Matrix Subtraction). Let \(\mathbf{A} = \begin{bmatrix} 4 & 8 & 3 \\ 5 & 1 & 9 \end{bmatrix}\) and \(\mathbf{B} = \begin{bmatrix} 2 & 1 & 6 \\ 3 & 0 & 7 \end{bmatrix}\). Then, their difference is:

\[ \mathbf{A} - \mathbf{B} = \begin{bmatrix} 4-2 & 8-1 & 3-6 \\ 5-3 & 1-0 & 9-7 \end{bmatrix} = \begin{bmatrix} 2 & 7 & -3 \\ 2 & 1 & 2 \end{bmatrix}. \]

This operation on a \(2 \times 3\) matrix requires \(2 \times 3 = 6\) subtractions, consistent with the \(O(mp)\) complexity for \(m=2\) and \(p=3\).

Scalar-Matrix Multiplication. Any matrix \(\mathbf{A} \in \mathbb{R}^{m \times p}\) can be multiplied by a scalar \(\alpha \in \mathbb{R}\). The product \(\mathbf{C} = \alpha\mathbf{A}\) is defined by \(C_{ij} = \alpha A_{ij}\).

  • Properties: Scalar-matrix multiplication is associative (\(\alpha (\beta \mathbf{A}) = (\alpha \beta) \mathbf{A}\)) and distributive (\((\alpha + \beta) \mathbf{A} = \alpha \mathbf{A} + \beta \mathbf{A}\)).
  • Complexity: This operation requires \(mp\) multiplications, one for each element of the matrix. The complexity is \(O(mp)\).

Example 3.3 (Scalar-Matrix Multiplication). Let the scalar be \(\alpha = 3\), and let the matrices be \(\mathbf{A} = \begin{bmatrix} 1 & 2 \\ 3 & 0 \end{bmatrix}\) and \(\mathbf{B} = \begin{bmatrix} -1 & 4 \\ 2 & 1 \end{bmatrix}\). We want to verify the distributive property \(\alpha(\mathbf{A} + \mathbf{B}) = \alpha\mathbf{A} + \alpha\mathbf{B}\).

Left-Hand Side (LHS): First, we compute the sum \(\mathbf{A} + \mathbf{B}\).

\[ \mathbf{A} + \mathbf{B} = \begin{bmatrix} 1+(-1) & 2+4 \\ 3+2 & 0+1 \end{bmatrix} = \begin{bmatrix} 0 & 6 \\ 5 & 1 \end{bmatrix}. \]

Next, we multiply the result by the scalar \(\alpha\).

\[ \alpha(\mathbf{A} + \mathbf{B}) = 3 \begin{bmatrix} 0 & 6 \\ 5 & 1 \end{bmatrix} = \begin{bmatrix} 3 \cdot 0 & 3 \cdot 6 \\ 3 \cdot 5 & 3 \cdot 1 \end{bmatrix} = \begin{bmatrix} 0 & 18 \\ 15 & 3 \end{bmatrix}. \]

Right-Hand Side (RHS): First, we compute the scalar-matrix products \(\alpha\mathbf{A}\) and \(\alpha\mathbf{B}\) separately.

\[ \alpha\mathbf{A} = 3 \begin{bmatrix} 1 & 2 \\ 3 & 0 \end{bmatrix} = \begin{bmatrix} 3 & 6 \\ 9 & 0 \end{bmatrix}. \] \[ \alpha\mathbf{B} = 3 \begin{bmatrix} -1 & 4 \\ 2 & 1 \end{bmatrix} = \begin{bmatrix} -3 & 12 \\ 6 & 3 \end{bmatrix}. \]

Next, we add the resulting matrices.

\[ \alpha\mathbf{A} + \alpha\mathbf{B} = \begin{bmatrix} 3+(-3) & 6+12 \\ 9+6 & 0+3 \end{bmatrix} = \begin{bmatrix} 0 & 18 \\ 15 & 3 \end{bmatrix}. \]

Since the results for the LHS and RHS are identical, the distributive property is verified. The total number of operations is consistent with the \(O(mp)\) complexity.

The Transpose Operator. The transpose of an \(m \times p\) matrix \(\mathbf{A}\), denoted \(\mathbf{A}^\top\), is the \(p \times m\) matrix obtained by swapping the rows and columns of \(\mathbf{A}\). Formally, \((\mathbf{A}^\top)_{ij} = A_{ji}\).

  • Properties: \((\mathbf{A}^\top)^\top = \mathbf{A}\) and \((\mathbf{A}+\mathbf{B})^\top = \mathbf{A}^\top + \mathbf{B}^\top\).
  • Complexity: Transposition is a data movement operation, not an arithmetic one. It requires no FLOPs and has a complexity of \(O(1)\) in terms of arithmetic, though it often incurs a memory access cost of \(O(mp)\).

Example 3.4 (Matrix Transpose). If \(\mathbf{A} = \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{bmatrix}\), then its transpose is \(\mathbf{A}^\top = \begin{bmatrix} 1 & 4 \\ 2 & 5 \\ 3 & 6 \end{bmatrix}\). The original \(2 \times 3\) matrix becomes a \(3 \times 2\) matrix.

Example 3.5 (Symmetric Matrix). Consider the following \(3 \times 3\) matrix:

\[ \mathbf{A} = \begin{bmatrix} 5 & \textcolor{blue}{2} & \textcolor{red}{-7} \\ \textcolor{blue}{2} & 1 & \textcolor{green}{4} \\ \textcolor{red}{-7} & \textcolor{green}{4} & 9 \end{bmatrix}. \]

To check if it is symmetric, we compute its transpose:

\[ \mathbf{A}^\top = \begin{bmatrix} 5 & 2 & -7 \\ 2 & 1 & 4 \\ -7 & 4 & 9 \end{bmatrix}. \]

Since \(\mathbf{A} = \mathbf{A}^\top\), the matrix is symmetric. Notice how the elements are mirrored across the main diagonal.

3.2 Matrix Products: The Engine of Transformation

Matrix products are the most computationally intensive, yet most powerful, of the basic matrix operations. They are the mechanism by which matrices transform vectors and other matrices, forming the core computation in linear models and neural network layers.

3.2.1 Matrix-Vector Multiplication

The product of an \(m \times p\) matrix \(\mathbf{A}\) and a \(p\)-vector \(\mathbf{x}\) results in an \(m\)-vector \(\mathbf{y}\). For the multiplication to be valid, the number of columns in the matrix must match the dimension of the vector. The resulting vector \(\mathbf{y} = \mathbf{A}\mathbf{x}\) can be interpreted in two essential ways.

The Row-Wise View (Inner Products): Each element \(y_i\) of the resulting vector is the inner product of the \(i\)-th row of \(\mathbf{A}\) with the vector \(\mathbf{x}\).

\[ y_i = \sum_{j=1}^p A_{ij} x_j = \langle \mathbf{A}_{i,:}, \mathbf{x} \rangle. \]

The Column-Wise View (Linear Combination): The resulting vector \(\mathbf{y}\) is a linear combination of the columns of \(\mathbf{A}\),

\[ \mathbf{A} = \begin{bmatrix} | & | & & | \\ \mathbf{a}_1 & \mathbf{a}_2 & \cdots & \mathbf{a}_p \\ | & | & & | \end{bmatrix}, \]

where the coefficients of the combination are the elements of \(\mathbf{x}\).

\[ \mathbf{y} = x_1\mathbf{a}_1 + x_2\mathbf{a}_2 + \dots + x_p\mathbf{a}_p = \sum_{j=1}^p x_j \mathbf{a}_j. \]

This second view is crucial for understanding how matrices act as linear transformations. The matrix \(\mathbf{A}\) transforms the vector \(\mathbf{x}\) from its original space (\(\mathbb{R}^p\)) into a new vector \(\mathbf{y}\) in the target space (\(\mathbb{R}^m\)) by combining its column vectors.

  • Complexity: Let’s focus on the row-wise view for clarity. To compute each of the \(m\) elements of \(\mathbf{y}\), we perform an inner product of length \(p\), which costs \(2p-1\) FLOPs. The total cost is \(m(2p-1)\) FLOPs. The complexity is therefore \(O(mp)\).

Example 3.6 (Matrix-Vector Product). Let \(\mathbf{A} = \begin{bmatrix} 1 & -1 & 2 \\ 0 & 3 & 1 \end{bmatrix}\) and \(\mathbf{x} = \begin{bmatrix} 2 \\ 1 \\ 0 \end{bmatrix}\). We wish to compute the product \(\mathbf{y} = \mathbf{A}\mathbf{x}\).

Can we perform the multiplication? The rule for matrix-vector multiplication requires that the number of columns in the matrix must equal the number of elements (rows) in the vector.

  • The matrix \(\mathbf{A}\) has dimensions \(2 \times 3\) (\(m=2\) rows, \(p=3\) columns).
  • The vector \(\mathbf{x}\) has dimensions \(3 \times 1\) (\(p=3\) rows).

Since the number of columns of \(\mathbf{A}\) (3) matches the number of rows of \(\mathbf{x}\) (3), the multiplication is valid.

What is the dimension of the resulting vector \(\mathbf{y}\)? The resulting vector will have a dimension equal to the number of rows of the matrix.

  • The matrix \(\mathbf{A}\) has \(m=2\) rows.

Therefore, the resulting vector \(\mathbf{y}\) will be a 2-dimensional vector (i.e., it will have dimensions \(2 \times 1\)).

Computation: Now we can compute the product using both interpretation methods.

Row-wise view: Each element of \(\mathbf{y}\) is the inner product of the corresponding row of \(\mathbf{A}\) with \(\mathbf{x}\).

\[ \begin{aligned} y_1 &= (\text{row 1 of } \mathbf{A}) \cdot \mathbf{x} = (1)(2) + (-1)(1) + (2)(0) = 1 \\ y_2 &= (\text{row 2 of } \mathbf{A}) \cdot \mathbf{x} = (0)(2) + (3)(1) + (1)(0) = 3 \end{aligned} \]

Column-wise view: The vector \(\mathbf{y}\) is a linear combination of the columns of \(\mathbf{A}\), with the elements of \(\mathbf{x}\) as coefficients.

\[ \begin{aligned} \mathbf{y} &= x_1(\text{col 1 of } \mathbf{A}) + x_2(\text{col 2 of } \mathbf{A}) + x_3(\text{col 3 of } \mathbf{A}) \Rightarrow \\ \mathbf{y} &= 2 \begin{bmatrix} 1 \\ 0 \end{bmatrix} + 1 \begin{bmatrix} -1 \\ 3 \end{bmatrix} + 0 \begin{bmatrix} 2 \\ 1 \end{bmatrix} = \begin{bmatrix} 2 \\ 0 \end{bmatrix} + \begin{bmatrix} -1 \\ 3 \end{bmatrix} + \begin{bmatrix} 0 \\ 0 \end{bmatrix} = \begin{bmatrix} 1 \\ 3 \end{bmatrix}. \end{aligned} \]

Both methods yield the same result, the \(2 \times 1\) vector \(\mathbf{y} = \begin{bmatrix} 1 \\ 3 \end{bmatrix}\).

Example 3.7 (Combined Matrix Operations). Given the scalar \(\alpha = 2\), the matrices \(\mathbf{A} = \begin{bmatrix} 1 & 0 & 2 \\ -1 & 3 & 1 \end{bmatrix}\) and \(\mathbf{B} = \begin{bmatrix} 4 & 1 & 1 \\ 0 & 2 & 5 \end{bmatrix}\), and the vector \(\mathbf{x} = \begin{bmatrix} 1 \\ 2 \\ -1 \end{bmatrix}\), compute the resulting vector \(\mathbf{y}\) from the expression:

\[ \mathbf{y} = (\alpha\mathbf{A} - \mathbf{B})\mathbf{x}. \]

Show each step of the calculation clearly.

We must follow the order of operations, starting with the expression inside the parentheses. First, we multiply the matrix \(\mathbf{A}\) by the scalar \(\alpha = 2\).

\[ \alpha\mathbf{A} = 2 \begin{bmatrix} 1 & 0 & 2 \\ -1 & 3 & 1 \end{bmatrix} = \begin{bmatrix} 2 \cdot 1 & 2 \cdot 0 & 2 \cdot 2 \\ 2 \cdot (-1) & 2 \cdot 3 & 2 \cdot 1 \end{bmatrix} = \begin{bmatrix} 2 & 0 & 4 \\ -2 & 6 & 2 \end{bmatrix}. \]

Next, we subtract the matrix \(\mathbf{B}\) from the result of Step 1. Let’s call the resulting matrix \(\mathbf{C}\).

\[ \begin{aligned} \mathbf{C} &= \alpha\mathbf{A} - \mathbf{B} = \begin{bmatrix} 2 & 0 & 4 \\ -2 & 6 & 2 \end{bmatrix} - \begin{bmatrix} 4 & 1 & 1 \\ 0 & 2 & 5 \end{bmatrix} \\ &= \begin{bmatrix} 2-4 & 0-1 & 4-1 \\ -2-0 & 6-2 & 2-5 \end{bmatrix} = \begin{bmatrix} -2 & -1 & 3 \\ -2 & 4 & -3 \end{bmatrix}. \end{aligned} \]

Finally, we multiply our intermediate matrix \(\mathbf{C}\) by the vector \(\mathbf{x}\). The matrix \(\mathbf{C}\) has dimensions \(2 \times 3\). The vector \(\mathbf{x}\) has dimensions \(3 \times 1\). Since the number of columns of \(\mathbf{C}\) (3) matches the number of rows of \(\mathbf{x}\) (3), the multiplication is valid. The resulting vector \(\mathbf{y}\) will have dimensions \(2 \times 1\). We compute the components of \(\mathbf{y}\) using the row-wise (inner product) view:

\[ \begin{aligned} y_1 &= (-2)(1) + (-1)(2) + (3)(-1) = -2 - 2 - 3 = -7 \\ y_2 &= (-2)(1) + (4)(2) + (-3)(-1) = -2 + 8 + 3 = 9 \end{aligned} \]

The resulting vector is \(\mathbf{y} = \begin{bmatrix} -7 \\ 9 \end{bmatrix}\).

Example 3.8 (Scalar and Scaled Identity Matrix Multiplication). We want to demonstrate that multiplying a matrix \(\mathbf{A}\) by a scalar \(\alpha\) is identical to pre-multiplying \(\mathbf{A}\) by an identity matrix that has been scaled by \(\alpha\). That is, we will verify that:

\[ \alpha\mathbf{A} = (\alpha\mathbf{I})\mathbf{A} \]

For illustration purposes, let the scalar be \(\alpha = 5\) and the matrix be \(\mathbf{A} = \begin{bmatrix} 1 & 2 & 3 \\ 4 & 0 & -1 \end{bmatrix}\).

For the scalar-matrix multiplication (\(\alpha\mathbf{A}\)), we have:

\[ \alpha\mathbf{A} = 5 \begin{bmatrix} 1 & 2 & 3 \\ 4 & 0 & -1 \end{bmatrix} = \begin{bmatrix} 5 & 10 & 15 \\ 20 & 0 & -5 \end{bmatrix}. \]

For the other side:

  • For the product \((\alpha\mathbf{I})\mathbf{A}\) to be valid, the number of columns of \((\alpha\mathbf{I})\) must match the number of rows of \(\mathbf{A}\). Since \(\mathbf{A}\) has \(m=2\) rows, our identity matrix \(\mathbf{I}\) must be a \(2 \times 2\) matrix. Now, we scale this identity matrix by \(\alpha=5\). \[ \alpha\mathbf{I} = 5 \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix} = \begin{bmatrix} 5 & 0 \\ 0 & 5 \end{bmatrix}. \]
  • We compute the product of the scaled identity matrix and \(\mathbf{A}\). \[ (\alpha\mathbf{I})\mathbf{A} = \begin{bmatrix} 5 & 0 \\ 0 & 5 \end{bmatrix} \begin{bmatrix} 1 & 2 & 3 \\ 4 & 0 & -1 \end{bmatrix}. \]

    Let’s compute the elements of the resulting \(2 \times 3\) matrix:

    \[ \begin{aligned} C_{11} &= (5)(1) + (0)(4) = 5 \\ C_{12} &= (5)(2) + (0)(0) = 10 \\ C_{13} &= (5)(3) + (0)(-1) = 15 \\ C_{21} &= (0)(1) + (5)(4) = 20 \\ C_{22} &= (0)(2) + (5)(0) = 0 \\ C_{23} &= (0)(3) + (5)(-1) = -5 \end{aligned} \]

    The resulting matrix is \(\mathbf{C} = \begin{bmatrix} 5 & 10 & 15 \\ 20 & 0 & -5 \end{bmatrix}\).

Since both calculations yield the exact same matrix, we have demonstrated the equivalence.

Example 3.9 (Diagonal Matrix Multiplication). We want to demonstrate that multiplying a vector \(\mathbf{x}\) by a diagonal matrix \(\mathbf{D}\) is computationally equivalent to performing an element-wise multiplication between the diagonal entries of \(\mathbf{D}\) and the elements of \(\mathbf{x}\).

Let the diagonal matrix be \(\mathbf{D} = \begin{bmatrix} 2 & 0 & 0 \\ 0 & 0.5 & 0 \\ 0 & 0 & -1 \end{bmatrix}\) and \(\mathbf{x} = \begin{bmatrix} 10 \\ 4 \\ 6 \end{bmatrix}\). We compute the product using the standard row-wise (inner product) view.

\[ \begin{aligned} \mathbf{y} = \mathbf{D}\mathbf{x} &= \begin{bmatrix} 2 & 0 & 0 \\ 0 & 0.5 & 0 \\ 0 & 0 & -1 \end{bmatrix} \begin{bmatrix} 10 \\ 4 \\ 6 \end{bmatrix} \\ &= \begin{bmatrix} (2)(10) + (0)(4) + (0)(6) \\ (0)(10) + (0.5)(4) + (0)(6) \\ (0)(10) + (0)(4) + (-1)(6) \end{bmatrix} \\ &= \begin{bmatrix} 20 \\ 2 \\ -6 \end{bmatrix}. \end{aligned} \]

For the element-wise multiplication, first we extract the diagonal elements of \(\mathbf{D}\) into a vector, let’s call it \(\mathbf{d}\).

\[ \mathbf{d} = \text{diag}(\mathbf{D}) = \begin{bmatrix} 2 \\ 0.5 \\ -1 \end{bmatrix}. \]

Next, we perform an element-wise product (also known as the Hadamard product, often denoted by \(\odot\)) between the vectors \(\mathbf{d}\) and \(\mathbf{x}\).

\[ \mathbf{y} = \mathbf{d} \odot \mathbf{x} = \begin{bmatrix} 2 \\ 0.5 \\ -1 \end{bmatrix} \odot \begin{bmatrix} 10 \\ 4 \\ 6 \end{bmatrix} = \begin{bmatrix} 2 \cdot 10 \\ 0.5 \cdot 4 \\ -1 \cdot 6 \end{bmatrix} = \begin{bmatrix} 20 \\ 2 \\ -6 \end{bmatrix}. \]

Both methods yield the exact same result. The key takeaway is that the sparse structure of the diagonal matrix simplifies the general matrix-vector multiplication (an \(O(p^2)\) operation for a dense square matrix) into a much more efficient element-wise product (an \(O(p)\) operation).

This equivalence is the mathematical foundation for adaptive optimization methods widely used in AI. In particular, we have seen that the basic update rule for gradient descent is:

\[ \mathbf{x}_{k+1} = \mathbf{x}_k - \eta \cdot \nabla f(\mathbf{x}_k). \]

Here, \(\eta\) is a single scalar learning rate. This means every parameter (or coordinate) in the vector \(\mathbf{x}_k\) is updated with the same step size, scaled only by its corresponding gradient entry in \(\nabla f(\mathbf{x}_k)\).

In many complex optimization problems, however, the loss function’s landscape is not uniform. It might be very steep along one coordinate direction but very flat along another. Thus, for a steep direction, a large step size (\(\eta\)) could cause the optimizer to overshoot the minimum and become unstable. In contrast, for a flat direction, the same small step size would lead to painfully slow progress. The ideal solution is to use a different step size for each coordinate: a small step for the steep directions and a large step for the flat ones.

We can achieve this by replacing the scalar step size \(\eta\) with a vector of step sizes, \(\boldsymbol{\eta}_{\text{vec}} = [\eta_1, \eta_2, \dots, \eta_p]^\top\). The update rule then becomes an element-wise product:

\[ \mathbf{x}_{k+1} = \mathbf{x}_k - \boldsymbol{\eta}_{\text{vec}} \odot \nabla f(\mathbf{x}_k) \]

Based on the equivalence we just demonstrated, this is identical to writing the update in matrix form:

\[ \mathbf{x}_{k+1} = \mathbf{x}_k - \mathbf{D}_{\eta} \nabla f(\mathbf{x}_k), \]

where \(\mathbf{D}_{\eta}\) is a diagonal matrix with the individual step sizes on its diagonal:

\[ \mathbf{D}_{\eta} = \begin{bmatrix} \eta_1 & 0 & \dots & 0 \\ 0 & \eta_2 & \dots & 0 \\ \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \dots & \eta_p \end{bmatrix}. \]

This formalizes the idea of per-coordinate scaling. Advanced optimization algorithms used to train deep neural networks, such as AdaGrad, RMSprop, and Adam, are built on this principle. At each step, they dynamically compute an effective diagonal matrix of step sizes based on the history of the gradients. This allows them to “adapt” the learning rate for each individual weight in the neural network, taking small, careful steps for sensitive parameters and larger, more confident steps for others, leading to significantly faster and more reliable convergence.

Example 3.10 (The Challenge of an Anisotropic Loss Function). This example demonstrates the practical power of per-coordinate scaling. We will show how a single, scalar learning rate can struggle with an imbalanced optimization problem, while adaptive, per-coordinate rates can converge much more effectively.

Consider the task of finding the minimum of a simple 2D quadratic function. This function is highly anisotropic, meaning it forms a long, narrow valley: it is very steep in one direction and very flat in another. Consider the objective function: \(f(\mathbf{x}) = 50x_1^2 + 0.5x_2^2\). For this function, the true minimum is: \(\mathbf{x}^\star = \begin{bmatrix} 0 \\ 0 \end{bmatrix}\) (why?) Then, the gradient can be computed as:

\[ \nabla f(\mathbf{x}) = \begin{bmatrix} \frac{\partial f}{\partial x_1} \\ \frac{\partial f}{\partial x_2} \end{bmatrix} = \begin{bmatrix} 100x_1 \\ x_2 \end{bmatrix}. \]

For a starting point \(\mathbf{x}_0 = \begin{bmatrix} 1 \\ 10 \end{bmatrix}\), the initial function value is \(f(\mathbf{x}_0) = 50(1)^2 + 0.5(10)^2 = 50 + 50 = 100\). Notice the imbalance: the gradient’s first component is 100 times more sensitive to its input \(x_1\) than the second component is to \(x_2\). This imbalance creates the narrow valley shape.

Assume the standard Gradient Descent method with a single scalar step size. The update rule is \(\mathbf{x}_{k+1} = \mathbf{x}_k - \eta \cdot \nabla f(\mathbf{x}_k)\). To ensure stability, we must choose a very small step size \(\eta\). If it is too large, the update for the steep \(x_1\) direction will “overshoot” the minimum and diverge. The stability is dictated by the largest gradient component, so we are forced to pick a small value, say \(\eta = 0.015\).

Iteration 1:

  • Initial Gradient: \(\nabla f(\mathbf{x}_0) = \begin{bmatrix} 100 \cdot 1 \\ 10 \end{bmatrix} = \begin{bmatrix} 100 \\ 10 \end{bmatrix}\).
  • Update: \[ \mathbf{x}_1 = \begin{bmatrix} 1 \\ 10 \end{bmatrix} - 0.015 \begin{bmatrix} 100 \\ 10 \end{bmatrix} = \begin{bmatrix} 1 - 1.5 \\ 10 - 0.15 \end{bmatrix} = \begin{bmatrix} -0.5 \\ 9.85 \end{bmatrix}. \]
  • New Function Value: \(f(\mathbf{x}_1) = 50(-0.5)^2 + 0.5(9.85)^2 = 12.5 + 48.51125 = 61.01125\).

Iteration 2:

  • New Gradient: \(\nabla f(\mathbf{x}_1) = \begin{bmatrix} 100 \cdot (-0.5) \\ 9.85 \end{bmatrix} = \begin{bmatrix} -50 \\ 9.85 \end{bmatrix}\).
  • Update: \[ \mathbf{x}_2 = \begin{bmatrix} -0.5 \\ 9.85 \end{bmatrix} - 0.015 \begin{bmatrix} -50 \\ 9.85 \end{bmatrix} = \begin{bmatrix} 0.25 \\ 9.70225 \end{bmatrix}. \]
  • New Function Value: \(f(\mathbf{x}_2) = 50(0.25)^2 + 0.5(9.70225)^2 = 3.125 + 47.0668 \approx 50.1918\).

After two iterations, the \(x_1\) coordinate is oscillating and slowly converging toward 0 (\(1 \to -0.5 \to 0.25\)). However, the \(x_2\) coordinate is making painfully slow progress (\(10 \to 9.85 \to 9.70\)). The small step size required by the steep \(x_1\) direction cripples the progress in the flat \(x_2\) direction.

Let’s now focus on per-coordinate Gradient Descent. The update rule is \(\mathbf{x}_{k+1} = \mathbf{x}_k - \mathbf{D}_{\eta} \nabla f(\mathbf{x}_k)\), which is equivalent to an element-wise product \(\mathbf{x}_{k+1} = \mathbf{x}_k - \boldsymbol{\eta}_{\text{vec}} \odot \nabla f(\mathbf{x}_k)\).

We can now choose different step sizes for each coordinate. We’ll use the same small step for the steep \(x_1\) direction but a much larger, more aggressive step for the flat \(x_2\) direction. Let’s choose the vector of step sizes \(\boldsymbol{\eta}_{\text{vec}} = \begin{bmatrix} 0.015 \\ 0.5 \end{bmatrix}\). This corresponds to the diagonal matrix \(\mathbf{D}_{\eta} = \begin{bmatrix} 0.015 & 0 \\ 0 & 0.5 \end{bmatrix}\).

Iteration 1:

  • Initial Gradient: \(\nabla f(\mathbf{x}_0) = \begin{bmatrix} 100 \\ 10 \end{bmatrix}\).
  • Update: \[ \mathbf{x}_1 = \begin{bmatrix} 1 \\ 10 \end{bmatrix} - \begin{bmatrix} 0.015 \\ 0.5 \end{bmatrix} \odot \begin{bmatrix} 100 \\ 10 \end{bmatrix} = \begin{bmatrix} 1 - 1.5 \\ 10 - 5 \end{bmatrix} = \begin{bmatrix} -0.5 \\ 5 \end{bmatrix}. \]
  • New Function Value: \(f(\mathbf{x}_1) = 50(-0.5)^2 + 0.5(5)^2 = 12.5 + 12.5 = 25\).

Iteration 2:

  • New Gradient: \(\nabla f(\mathbf{x}_1) = \begin{bmatrix} 100 \cdot (-0.5) \\ 5 \end{bmatrix} = \begin{bmatrix} -50 \\ 5 \end{bmatrix}\).
  • Update: \[ \mathbf{x}_2 = \begin{bmatrix} -0.5 \\ 5 \end{bmatrix} - \begin{bmatrix} 0.015 \\ 0.5 \end{bmatrix} \odot \begin{bmatrix} -50 \\ 5 \end{bmatrix} = \begin{bmatrix} 0.25 \\ 2.5 \end{bmatrix}. \]
  • New Function Value: \(f(\mathbf{x}_2) = 50(0.25)^2 + 0.5(2.5)^2 = 3.125 + 3.125 = 6.25\).

Thus, by using a learning rate adapted to the geometry of each coordinate, the per-coordinate method reduced the function value far more significantly.

Table 3.1: Comparison of function values after two iterations of gradient descent.
Iter.Scalar \(\eta\) (\(f(\mathbf{x})\))\(\boldsymbol{\eta}_{\text{vec}}\) (\(f(\mathbf{x})\))
0100100
161.0125
250.196.25

This toy example perfectly illustrates why modern optimizers like Adam, AdaGrad, and RMSprop, which dynamically build an effective diagonal matrix of learning rates, are the default choice for training deep neural networks. They automate the process of adapting to the thousands or millions of different sensitivities found in a complex loss landscape, allowing for much faster and more robust convergence.

Code session · Example 3.10 Skip to Section 3.3

One step size or one per coordinate

Example 3.10's two runs of gradient descent from (1, 10), carried on for 30 steps: one step size, 0.015, for both coordinates, or 0.015 for the steep coordinate and 0.5 for the flat one.

show setup
import numpy as np
1f = lambda x: 50 * x[0] ** 2 + 0.5 * x[1] ** 2
2grad = lambda x: np.array([100 * x[0], x[1]])
3steps = {"scalar": 0.015, "per-coordinate": np.array([0.015, 0.5])}
4vals = {}
5for name, eta in steps.items():
6    x = np.array([1.0, 10.0])
7    vals[name] = [f(x)]
8    for k in range(30):
9        x = x - eta * grad(x)              # eta * grad is entrywise
10        vals[name].append(f(x))
11    v = vals[name]
12    print(f"{name:15} f = {v[0]:.2f}, {v[1]:.2f}, {v[2]:.2f}, ...  after 30 steps {v[30]:.3g}")
Recorded output
scalar          f = 100.00, 61.01, 50.19, ...  after 30 steps 20.2
per-coordinate  f = 100.00, 25.00, 6.25, ...  after 30 steps 8.67e-17
10⁻¹⁸ 10⁻¹⁵ 10⁻¹² 10⁻⁹ 10⁻⁶ 10⁻³ 1 10³ 0 5 10 15 20 25 30 f(x) (log scale) step k one step size (η = 0.015) per-coordinate (0.015, 0.5)

f against step, on a log scale. The first three values of each run are Table 3.1. Both runs take the same step along the steep coordinate, which halves and flips sign at every step. With one shared step size the flat coordinate shrinks by only 1.5% per step, so f is still 20.2 after 30 steps. With its own step of 0.5 the flat coordinate halves too, and f is divided by 4 at every step.

Recorded on an Apple M1 Max laptop, macOS 26.6.2, Python 3.13.7, NumPy 2.4.6, 2026-11-30.

3.3 Revisiting Key Concepts with Matrix Notation

Now that we have formally defined matrices and the crucial matrix-vector product, we possess a more powerful language to describe the concepts introduced in previous chapters. Revisiting these ideas will reveal how matrices allow us to express complex operations on entire datasets in a compact and computationally efficient manner.

3.3.1 Revisiting 1: Linear Combinations as a Matrix-Vector Product

In Chapter 1, we defined a linear combination of vectors \(\mathbf{x}_1, \dots, \mathbf{x}_p \in \mathbb{R}^m\) with scalars \(\alpha_1, \dots, \alpha_p\) as the sum:

\[ \mathbf{y} = \alpha_1\mathbf{x}_1 + \alpha_2\mathbf{x}_2 + \dots + \alpha_p\mathbf{x}_p. \]

We saw that finding the coefficients \(\alpha_i\) to form a target vector \(\mathbf{y}\) required solving a system of scalar linear equations.

The New Perspective with Matrices. Recall the column-wise view of matrix-vector multiplication: the result of \(\mathbf{X}\boldsymbol{\alpha}\) is a linear combination of the columns of \(\mathbf{X}\), with coefficients given by the elements of \(\boldsymbol{\alpha}\). This allows us to rewrite the entire system in a single, elegant equation.

If we form a matrix \(\mathbf{X}\) by stacking our vectors as its columns, and place the scalars in a vector \(\boldsymbol{\alpha}\):

\[ \mathbf{X} = \begin{bmatrix} | & | & & | \\ \mathbf{x}_1 & \mathbf{x}_2 & \cdots & \mathbf{x}_p \\ | & | & & | \end{bmatrix} \in \mathbb{R}^{m \times p}, \quad \boldsymbol{\alpha} = \begin{bmatrix} \alpha_1 \\ \alpha_2 \\ \vdots \\ \alpha_p \end{bmatrix} \in \mathbb{R}^p, \]

then the linear combination is precisely the matrix-vector product:

\[ \mathbf{y} = \mathbf{X}\boldsymbol{\alpha}. \]

The problem of finding the coefficients to represent \(\mathbf{y}\) is now transformed into the problem of solving the linear system \(\mathbf{X}\boldsymbol{\alpha} = \mathbf{y}\) for the unknown vector \(\boldsymbol{\alpha}\).

Example 3.11 (Linear Combination as a System). Let’s revisit the example of expressing \(\mathbf{y} = \begin{bmatrix} 5 \\ 4 \end{bmatrix}\) as a combination of \(\mathbf{x}_1 = \begin{bmatrix} 2 \\ 0 \end{bmatrix}\) and \(\mathbf{x}_2 = \begin{bmatrix} -1 \\ 2 \end{bmatrix}\).

Old Formulation (System of Equations):

\[ \begin{aligned} 2\alpha_1 - \alpha_2 &= 5 \\ 0\alpha_1 + 2\alpha_2 &= 4 \end{aligned} \]

New Formulation (Matrix-Vector Equation): We construct the matrix \(\mathbf{X} = \begin{bmatrix} 2 & -1 \\ 0 & 2 \end{bmatrix}\) and the vector \(\boldsymbol{\alpha} = \begin{bmatrix} \alpha_1 \\ \alpha_2 \end{bmatrix}\). The problem becomes:

\[ \begin{bmatrix} 2 & -1 \\ 0 & 2 \end{bmatrix} \begin{bmatrix} \alpha_1 \\ \alpha_2 \end{bmatrix} = \begin{bmatrix} 5 \\ 4 \end{bmatrix}. \]

This compact notation represents the exact same system of equations but is far cleaner and more amenable to computational linear algebra techniques.

3.3.2 Revisiting 2: The Least-Squares Problem in Matrix Form

We formulated the least-squares objective as a sum over \(n\) individual data points \((\mathbf{a}_i, y_i)\):

\[ f(\mathbf{w}) = \frac{1}{n} \sum_{i=1}^n (y_i - \mathbf{a}_i^\top \mathbf{w})^2. \]

The gradient was similarly a sum over all data points:

\[ \nabla f(\mathbf{w}) = \frac{-2}{n} \sum_{i=1}^n (y_i - \mathbf{a}_i^\top\mathbf{w})\mathbf{a}_i. \]

The New Perspective with Matrices. Let’s assemble our entire dataset into a single data matrix \(\mathbf{A}\) and a vector of outcomes \(\mathbf{y}\). Each row of \(\mathbf{A}\) is one of our feature vectors \(\mathbf{a}_i^\top\).

\[ \mathbf{A} = \begin{bmatrix} \text{--- } \mathbf{a}_1^\top \text{ ---} \\ \text{--- } \mathbf{a}_2^\top \text{ ---} \\ \vdots \\ \text{--- } \mathbf{a}_n^\top \text{ ---} \end{bmatrix} \in \mathbb{R}^{n \times p}, \quad \mathbf{y} = \begin{bmatrix} y_1 \\ y_2 \\ \vdots \\ y_n \end{bmatrix} \in \mathbb{R}^n. \]

Now, consider the matrix-vector product \(\mathbf{A}\mathbf{w}\). The \(i\)-th element of this resulting vector is the inner product of the \(i\)-th row of \(\mathbf{A}\) with \(\mathbf{w}\), which is precisely \(\mathbf{a}_i^\top \mathbf{w}\). Therefore, the product \(\mathbf{A}\mathbf{w}\) is a single vector containing all \(n\) of our model’s predictions:

\[ \mathbf{A}\mathbf{w} = \begin{bmatrix} \mathbf{a}_1^\top \mathbf{w} \\ \mathbf{a}_2^\top \mathbf{w} \\ \vdots \\ \mathbf{a}_n^\top \mathbf{w} \end{bmatrix} = \hat{\mathbf{y}}. \]

The difference between the true outcomes and our predictions is now a single vector subtraction, creating the residual vector \(\mathbf{r} = \mathbf{y} - \mathbf{A}\mathbf{w}\). The sum of squared errors, \(\sum (y_i - \hat{y}_i)^2\), is simply the squared \(\ell_2\)-norm of this residual vector, \(\|\mathbf{r}\|_2^2\).

Rewritten Objective:

\[ f(\mathbf{w}) = \frac{1}{n} \|\mathbf{y} - \mathbf{A}\mathbf{w}\|_2^2. \]

Rewritten Gradient: The summation form of the gradient can also be expressed compactly. It can be shown that it is equivalent to:

\[ \nabla f(\mathbf{w}) = \frac{-2}{n} \mathbf{A}^\top (\mathbf{y} - \mathbf{A}\mathbf{w}). \]

This matrix form is not only more elegant but is also how these computations are implemented in practice. Software libraries like NumPy can compute the matrix-vector products and matrix transpositions far more efficiently than an explicit loop over the data points.

3.3.3 Revisiting 3: Generalizing Quadratic Functions

In Chapter 1, we introduced a simple multivariate quadratic function of the form:

\[ f(\mathbf{x}) = \frac{1}{2}\langle \mathbf{x}, \mathbf{x} \rangle - \langle \mathbf{b}, \mathbf{x} \rangle = \frac{1}{2}\|\mathbf{x}\|_2^2 - \mathbf{b}^\top\mathbf{x}. \]

We showed that this function has a “bowl” shape with circular level sets, and its minimum is at \(\mathbf{x}^\star=\mathbf{b}\). The term \(\langle \mathbf{x}, \mathbf{x} \rangle\) can be written in matrix notation as \(\mathbf{x}^\top\mathbf{I}\mathbf{x}\), where \(\mathbf{I}\) is the identity matrix. This reveals that our simple quadratic was a special case where the curvature is uniform in all directions.

The New Perspective with Matrices. We can generalize this by replacing the identity matrix \(\mathbf{I}\) with any symmetric matrix \(\mathbf{H} \in \mathbb{R}^{p \times p}\). This gives us the general quadratic form:

\[ f(\mathbf{x}) = \frac{1}{2}\mathbf{x}^\top\mathbf{H}\mathbf{x} - \mathbf{b}^\top\mathbf{x}. \]

This is a much richer class of functions. The matrix \(\mathbf{H}\) controls the curvature of the function.

  • If \(\mathbf{H} = \mathbf{I}\), we recover our original function with circular level sets.
  • If \(\mathbf{H}\) is a diagonal matrix with unequal positive entries (like in the anisotropic gradient descent example), the level sets become ellipses aligned with the coordinate axes. The function is steeper in the directions corresponding to larger diagonal entries.
  • If \(\mathbf{H}\) is a non-diagonal symmetric matrix with \(\mathbf{x}^\top\mathbf{H}\mathbf{x} > 0\) for every \(\mathbf{x} \neq \mathbf{0}\), the level sets are rotated ellipses.

This general form is fundamental to optimization. The minimum of this function (if it exists) occurs where the gradient is zero. The gradient of this general form is \(\nabla f(\mathbf{x}) = \mathbf{H}\mathbf{x} - \mathbf{b}\). Setting it to zero gives the linear system \(\mathbf{H}\mathbf{x} = \mathbf{b}\), whose solution is the minimizer. We will discuss this further in the optimization sections.

3.3.4 Revisiting 4: The Second-Order Taylor Approximation

We introduced the first-order multivariate Taylor approximation:

\[ f(\mathbf{x}) \approx f(\mathbf{x}_0) + \langle \nabla f(\mathbf{x}_0), \mathbf{x}-\mathbf{x}_0 \rangle. \]

We mentioned that a more accurate, second-order approximation existed but did not have the tools to define it properly.

The New Perspective with Matrices. The second-order term captures the function’s curvature. This curvature is described by the Hessian matrix, which is the matrix of all second partial derivatives, denoted \(\mathbf{H}\) or \(\nabla^2 f(\mathbf{x})\). For \(p\) variables, the Hessian is a \(p \times p\) symmetric matrix:

\[ H_{ij} = \left(\nabla^2 f(\mathbf{x})\right)_{ij} = \frac{\partial^2 f}{\partial x_i \partial x_j}. \]

With the Hessian defined, we can now write the full second-order Taylor approximation:

\[ f(\mathbf{x}) \approx f(\mathbf{x}_0) + \nabla f(\mathbf{x}_0)^\top (\mathbf{x}-\mathbf{x}_0) + \frac{1}{2}(\mathbf{x}-\mathbf{x}_0)^\top \mathbf{H}_0 (\mathbf{x}-\mathbf{x}_0), \]

where \(\mathbf{H}_0 = \nabla^2 f(\mathbf{x}_0)\) is the Hessian evaluated at the center point \(\mathbf{x}_0\).

This is a profound connection: the local, second-order approximation of any smooth multivariate function is a general quadratic function. This means that by understanding the simple quadratic form \(f(\mathbf{x}) = \frac{1}{2}\mathbf{x}^\top\mathbf{H}\mathbf{x} - \mathbf{b}^\top\mathbf{x}\) (see Revisiting 3), we gain deep insight into the local behavior of much more complex functions that we seek to optimize in AI. Advanced optimization methods, like Newton’s method, are derived by directly minimizing this local quadratic model at each step.

3.4 Matrix-Matrix Multiplication

The product of an \(m \times n\) matrix \(\mathbf{A}\) and an \(n \times p\) matrix \(\mathbf{B}\) is an \(m \times p\) matrix \(\mathbf{C}\). The number of columns in the first matrix must match the number of rows in the second. Each element \(C_{ij}\) of the resulting matrix is the inner product of the \(i\)-th row of \(\mathbf{A}\) and the \(j\)-th column of \(\mathbf{B}\):

\[ C_{ij} = \sum_{k=1}^n A_{ik} B_{kj}. \]

To visualize this operation, we can represent the matrices by their constituent rows and columns. Let the rows of \(\mathbf{A}\) be denoted by \(\mathbf{a}_{i,:}^\top\) and the columns of \(\mathbf{B}\) by \(\mathbf{b}_{:,j}\).

\[ \mathbf{A} = \begin{bmatrix} \text{--- } \mathbf{a}_{1,:}^\top \text{ ---} \\ \text{--- } \mathbf{a}_{2,:}^\top \text{ ---} \\ \vdots \\ \text{--- } \mathbf{a}_{m,:}^\top \text{ ---} \end{bmatrix}, \quad \mathbf{B} = \begin{bmatrix} | & | & & | \\ \mathbf{b}_{:,1} & \mathbf{b}_{:,2} & \cdots & \mathbf{b}_{:,p} \\ | & | & & | \end{bmatrix}. \]

The resulting matrix \(\mathbf{C} = \mathbf{A}\mathbf{B}\) is then constructed by filling each entry \((i, j)\) with the inner product of the corresponding row from \(\mathbf{A}\) and column from \(\mathbf{B}\):

\[ \mathbf{C} = \begin{bmatrix} \langle \mathbf{a}_{1,:}, \mathbf{b}_{:,1} \rangle & \langle \mathbf{a}_{1,:}, \mathbf{b}_{:,2} \rangle & \cdots & \langle \mathbf{a}_{1,:}, \mathbf{b}_{:,p} \rangle \\ \langle \mathbf{a}_{2,:}, \mathbf{b}_{:,1} \rangle & \langle \mathbf{a}_{2,:}, \mathbf{b}_{:,2} \rangle & \cdots & \langle \mathbf{a}_{2,:}, \mathbf{b}_{:,p} \rangle \\ \vdots & \vdots & \ddots & \vdots \\ \langle \mathbf{a}_{m,:}, \mathbf{b}_{:,1} \rangle & \langle \mathbf{a}_{m,:}, \mathbf{b}_{:,2} \rangle & \cdots & \langle \mathbf{a}_{m,:}, \mathbf{b}_{:,p} \rangle \end{bmatrix}. \]

Example 3.12 (Matrix-Matrix Product). Let \(\mathbf{A} = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}\) and \(\mathbf{B} = \begin{bmatrix} 5 & 6 \\ 0 & 7 \end{bmatrix}\). The product \(\mathbf{C} = \mathbf{A}\mathbf{B}\) is a \(2 \times 2\) matrix computed as follows:

\[ \mathbf{C} = \begin{bmatrix} (\text{row 1 of } \mathbf{A}) \cdot (\text{col 1 of } \mathbf{B}) & (\text{row 1 of } \mathbf{A}) \cdot (\text{col 2 of } \mathbf{B}) \\ (\text{row 2 of } \mathbf{A}) \cdot (\text{col 1 of } \mathbf{B}) & (\text{row 2 of } \mathbf{A}) \cdot (\text{col 2 of } \mathbf{B}) \end{bmatrix}. \]

Calculating each inner product explicitly:

  • \(C_{11} = \begin{bmatrix} 1 & 2 \end{bmatrix} \begin{bmatrix} 5 \\ 0 \end{bmatrix} = (1)(5) + (2)(0) = 5\).
  • \(C_{12} = \begin{bmatrix} 1 & 2 \end{bmatrix} \begin{bmatrix} 6 \\ 7 \end{bmatrix} = (1)(6) + (2)(7) = 6 + 14 = 20\).
  • \(C_{21} = \begin{bmatrix} 3 & 4 \end{bmatrix} \begin{bmatrix} 5 \\ 0 \end{bmatrix} = (3)(5) + (4)(0) = 15\).
  • \(C_{22} = \begin{bmatrix} 3 & 4 \end{bmatrix} \begin{bmatrix} 6 \\ 7 \end{bmatrix} = (3)(6) + (4)(7) = 18 + 28 = 46\).

Assembling these values gives the final matrix:

\[ \mathbf{C} = \begin{bmatrix} 5 & 20 \\ 15 & 46 \end{bmatrix}. \]

This “row-by-column inner product” view is the most common way to compute matrix products by hand. However, just like with matrix-vector multiplication, there are other powerful interpretations:

  • Column-wise View: Each column of the resulting matrix \(\mathbf{C}\) is a linear combination of the columns of \(\mathbf{A}\), where the coefficients are the elements of the corresponding column of \(\mathbf{B}\). Specifically, the \(j\)-th column of \(\mathbf{C}\) is computed as \(\mathbf{c}_{:,j} = \mathbf{A} \mathbf{b}_{:,j}\).
  • Row-wise View: Each row of \(\mathbf{C}\) is a linear combination of the rows of \(\mathbf{B}\), where the coefficients are the elements of the corresponding row of \(\mathbf{A}\). The \(i\)-th row of \(\mathbf{C}\) is computed as \(\mathbf{c}_{i,:}^\top = \mathbf{a}_{i,:}^\top \mathbf{B}\).

Example 3.13 (Mismatched Dimensions). Consider the matrices:

\[ \mathbf{A} = \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{bmatrix} \quad \text{and} \quad \mathbf{B} = \begin{bmatrix} 7 & 8 \\ 9 & 10 \end{bmatrix}. \]

The dimensions are:

  • Matrix \(\mathbf{A}\) is \(2 \times \mathbf{3}\) (\(m=2\) rows, \(n=3\) columns).
  • Matrix \(\mathbf{B}\) is \(\mathbf{2} \times 2\) (\(k=2\) rows, \(p=2\) columns).

The inner dimension of \(\mathbf{A}\) (number of columns, \(n=3\)) does not match the inner dimension of \(\mathbf{B}\) (number of rows, \(k=2\)). This should signal us that this is not possible to perform the matrix-matrix multiplication. Nevertheless, let’s attempt to compute the first element, \(C_{11}\), of the would-be product matrix \(\mathbf{C} = \mathbf{A}\mathbf{B}\). According to the definition, this element should be the inner product of the first row of \(\mathbf{A}\) and the first column of \(\mathbf{B}\).

\[ C_{11} = \langle \mathbf{a}_{1,:}, \mathbf{b}_{:,1} \rangle \]

Let’s extract these two vectors:

  • The first row of \(\mathbf{A}\) is \(\mathbf{a}_{1,:} = \begin{bmatrix} 1 & 2 & 3 \end{bmatrix}\). This is a vector of length 3.
  • The first column of \(\mathbf{B}\) is \(\mathbf{b}_{:,1} = \begin{bmatrix} 7 \\ 9 \end{bmatrix}\). This is a vector of length 2.

Now, let’s try to compute their inner product:

\[ \langle \begin{bmatrix} 1 & 2 & 3 \end{bmatrix}, \begin{bmatrix} 7 \\ 9 \end{bmatrix} \rangle = (1)(7) + (2)(9) + (3)(?) \]

The operation breaks down. The third element of the row vector, the number 3, has no corresponding element in the column vector to be multiplied with. The inner product is undefined because the vectors have different lengths.

The length of any row vector from matrix \(\mathbf{A}\) is equal to its number of columns (\(n\)). The length of any column vector from matrix \(\mathbf{B}\) is equal to its number of rows (\(k\)). Since every element of the product \(\mathbf{C}\) requires an inner product between one of these rows and one of these columns, the operation is only possible if these vectors have the same length. Therefore, it is a strict requirement that \(n=k\).

Matrix multiplication is associative (\(( \mathbf{A}\mathbf{B} )\mathbf{C} = \mathbf{A}( \mathbf{B}\mathbf{C} )\)) and distributive (\(( \mathbf{A} + \mathbf{B} )\mathbf{C} = \mathbf{A} \mathbf{C} + \mathbf{B}\mathbf{C}\)), but it is not commutative in general (\(\mathbf{A}\mathbf{B} \neq \mathbf{B}\mathbf{A}\)). The transpose property is \((\mathbf{A}\mathbf{B})^\top = \mathbf{B}^\top\mathbf{A}^\top\).

Example 3.14 (The Associative Property). Let’s verify the associative property with the following matrices:

\[ \mathbf{A} = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}, \quad \mathbf{B} = \begin{bmatrix} 5 & 6 \\ 0 & 1 \end{bmatrix}, \quad \mathbf{C} = \begin{bmatrix} 2 & 0 \\ 1 & 3 \end{bmatrix}. \]

Compute \((\mathbf{A}\mathbf{B})\mathbf{C}\): First, compute the product inside the parentheses, \(\mathbf{D} = \mathbf{A}\mathbf{B}\):

\[ \begin{aligned} \mathbf{D} &= \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} \begin{bmatrix} 5 & 6 \\ 0 & 1 \end{bmatrix} = \begin{bmatrix} (1)(5)+(2)(0) & (1)(6)+(2)(1) \\ (3)(5)+(4)(0) & (3)(6)+(4)(1) \end{bmatrix} \\ &= \begin{bmatrix} 5 & 8 \\ 15 & 22 \end{bmatrix}. \end{aligned} \]

Now, multiply the result by \(\mathbf{C}\):

\[ \begin{aligned} (\mathbf{A}\mathbf{B})\mathbf{C} &= \mathbf{D}\mathbf{C} = \begin{bmatrix} 5 & 8 \\ 15 & 22 \end{bmatrix} \begin{bmatrix} 2 & 0 \\ 1 & 3 \end{bmatrix} \\ &= \begin{bmatrix} (5)(2)+(8)(1) & (5)(0)+(8)(3) \\ (15)(2)+(22)(1) & (15)(0)+(22)(3) \end{bmatrix} = \begin{bmatrix} 18 & 24 \\ 52 & 66 \end{bmatrix}. \end{aligned} \]

Compute \(\mathbf{A}(\mathbf{B}\mathbf{C})\): First, compute the product inside the parentheses, \(\mathbf{E} = \mathbf{B}\mathbf{C}\):

\[ \begin{aligned} \mathbf{E} &= \begin{bmatrix} 5 & 6 \\ 0 & 1 \end{bmatrix} \begin{bmatrix} 2 & 0 \\ 1 & 3 \end{bmatrix} = \begin{bmatrix} (5)(2)+(6)(1) & (5)(0)+(6)(3) \\ (0)(2)+(1)(1) & (0)(0)+(1)(3) \end{bmatrix} \\ &= \begin{bmatrix} 16 & 18 \\ 1 & 3 \end{bmatrix}. \end{aligned} \]

Now, pre-multiply the result by \(\mathbf{A}\):

\[ \begin{aligned} \mathbf{A}(\mathbf{B}\mathbf{C}) &= \mathbf{A}\mathbf{E} = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} \begin{bmatrix} 16 & 18 \\ 1 & 3 \end{bmatrix} \\ &= \begin{bmatrix} (1)(16)+(2)(1) & (1)(18)+(2)(3) \\ (3)(16)+(4)(1) & (3)(18)+(4)(3) \end{bmatrix} = \begin{bmatrix} 18 & 24 \\ 52 & 66 \end{bmatrix}. \end{aligned} \]

Example 3.15 (The Distributive Property). Let’s verify the distributive property with the following matrices:

\[ \mathbf{A} = \begin{bmatrix} 1 & 0 \\ 2 & 1 \end{bmatrix}, \quad \mathbf{B} = \begin{bmatrix} 3 & 2 \\ 0 & 4 \end{bmatrix}, \quad \mathbf{C} = \begin{bmatrix} 5 \\ -1 \end{bmatrix}. \]

Compute \((\mathbf{A} + \mathbf{B})\mathbf{C}\): First, compute the sum inside the parentheses, \(\mathbf{D} = \mathbf{A} + \mathbf{B}\):

\[ \mathbf{D} = \begin{bmatrix} 1+3 & 0+2 \\ 2+0 & 1+4 \end{bmatrix} = \begin{bmatrix} 4 & 2 \\ 2 & 5 \end{bmatrix}. \]

Now, multiply the result by \(\mathbf{C}\):

\[ (\mathbf{A} + \mathbf{B})\mathbf{C} = \mathbf{D}\mathbf{C} = \begin{bmatrix} 4 & 2 \\ 2 & 5 \end{bmatrix} \begin{bmatrix} 5 \\ -1 \end{bmatrix} = \begin{bmatrix} (4)(5)+(2)(-1) \\ (2)(5)+(5)(-1) \end{bmatrix} = \begin{bmatrix} 18 \\ 5 \end{bmatrix}. \]

Compute \(\mathbf{A}\mathbf{C} + \mathbf{B}\mathbf{C}\): First, compute the two separate products, \(\mathbf{A}\mathbf{C}\) and \(\mathbf{B}\mathbf{C}\):

\[ \mathbf{A}\mathbf{C} = \begin{bmatrix} 1 & 0 \\ 2 & 1 \end{bmatrix} \begin{bmatrix} 5 \\ -1 \end{bmatrix} = \begin{bmatrix} (1)(5)+(0)(-1) \\ (2)(5)+(1)(-1) \end{bmatrix} = \begin{bmatrix} 5 \\ 9 \end{bmatrix}. \] \[ \mathbf{B}\mathbf{C} = \begin{bmatrix} 3 & 2 \\ 0 & 4 \end{bmatrix} \begin{bmatrix} 5 \\ -1 \end{bmatrix} = \begin{bmatrix} (3)(5)+(2)(-1) \\ (0)(5)+(4)(-1) \end{bmatrix} = \begin{bmatrix} 13 \\ -4 \end{bmatrix}. \]

Now, add the two resulting vectors:

\[ \mathbf{A}\mathbf{C} + \mathbf{B}\mathbf{C} = \begin{bmatrix} 5 \\ 9 \end{bmatrix} + \begin{bmatrix} 13 \\ -4 \end{bmatrix} = \begin{bmatrix} 5+13 \\ 9-4 \end{bmatrix} = \begin{bmatrix} 18 \\ 5 \end{bmatrix}. \]

Example 3.16 (The Non-Commutative Property).

Example 3.16 (The Non-Commutative Property).

Unlike scalar multiplication, matrix multiplication is generally not commutative. Let’s demonstrate this with two matrices:

\[ \mathbf{A} = \begin{bmatrix} 1 & 2 \\ 0 & 3 \end{bmatrix}, \quad \mathbf{B} = \begin{bmatrix} 4 & 0 \\ 1 & 5 \end{bmatrix}. \]

First, compute \(\mathbf{A}\mathbf{B}\):

\[ \begin{aligned} \mathbf{A}\mathbf{B} &= \begin{bmatrix} 1 & 2 \\ 0 & 3 \end{bmatrix} \begin{bmatrix} 4 & 0 \\ 1 & 5 \end{bmatrix} \\ &= \begin{bmatrix} (1)(4)+(2)(1) & (1)(0)+(2)(5) \\ (0)(4)+(3)(1) & (0)(0)+(3)(5) \end{bmatrix} = \begin{bmatrix} 6 & 10 \\ 3 & 15 \end{bmatrix}. \end{aligned} \]

Next, compute \(\mathbf{B}\mathbf{A}\):

\[ \begin{aligned} \mathbf{B}\mathbf{A} &= \begin{bmatrix} 4 & 0 \\ 1 & 5 \end{bmatrix} \begin{bmatrix} 1 & 2 \\ 0 & 3 \end{bmatrix} \\ &= \begin{bmatrix} (4)(1)+(0)(0) & (4)(2)+(0)(3) \\ (1)(1)+(5)(0) & (1)(2)+(5)(3) \end{bmatrix} = \begin{bmatrix} 4 & 8 \\ 1 & 17 \end{bmatrix}. \end{aligned} \]

By direct comparison, it is clear that:

\[ \begin{bmatrix} 6 & 10 \\ 3 & 15 \end{bmatrix} \neq \begin{bmatrix} 4 & 8 \\ 1 & 17 \end{bmatrix}. \]

Therefore, \(\mathbf{A}\mathbf{B} \neq \mathbf{B}\mathbf{A}\). This property is a fundamental departure from scalar algebra and has profound implications in linear transformations and quantum mechanics.

Example 3.17 (The Transpose of a Product). Let’s verify the property \((\mathbf{A}\mathbf{B})^\top = \mathbf{B}^\top\mathbf{A}^\top\) using non-square matrices to make the change in dimensions clear:

\[ \mathbf{A} = \begin{bmatrix} 1 & 2 & 0 \\ 3 & 0 & 1 \end{bmatrix}, \quad \mathbf{B} = \begin{bmatrix} 1 & 1 \\ 0 & 2 \\ 5 & 0 \end{bmatrix}. \]

Compute \((\mathbf{A}\mathbf{B})^\top\): First, compute the product \(\mathbf{C} = \mathbf{A}\mathbf{B}\) (which will be a \(2 \times 2\) matrix):

\[ \begin{aligned} \mathbf{C} &= \begin{bmatrix} 1 & 2 & 0 \\ 3 & 0 & 1 \end{bmatrix} \begin{bmatrix} 1 & 1 \\ 0 & 2 \\ 5 & 0 \end{bmatrix} \\ &= \begin{bmatrix} (1)(1)+(2)(0)+(0)(5) & (1)(1)+(2)(2)+(0)(0) \\ (3)(1)+(0)(0)+(1)(5) & (3)(1)+(0)(2)+(1)(0) \end{bmatrix} \\ &= \begin{bmatrix} 1 & 5 \\ 8 & 3 \end{bmatrix}. \end{aligned} \]

Now, take the transpose of the result:

\[ (\mathbf{A}\mathbf{B})^\top = \mathbf{C}^\top = \begin{bmatrix} 1 & 8 \\ 5 & 3 \end{bmatrix}. \]

Compute \(\mathbf{B}^\top\mathbf{A}^\top\): First, find the transpose of each matrix individually:

\[ \mathbf{B}^\top = \begin{bmatrix} 1 & 0 & 5 \\ 1 & 2 & 0 \end{bmatrix}, \quad \mathbf{A}^\top = \begin{bmatrix} 1 & 3 \\ 2 & 0 \\ 0 & 1 \end{bmatrix}. \]

Now, multiply the transposes in the reversed order (a \(2 \times 3\) matrix times a \(3 \times 2\) matrix, which results in a valid \(2 \times 2\) matrix):

\[ \begin{aligned} \mathbf{B}^\top\mathbf{A}^\top &= \begin{bmatrix} 1 & 0 & 5 \\ 1 & 2 & 0 \end{bmatrix} \begin{bmatrix} 1 & 3 \\ 2 & 0 \\ 0 & 1 \end{bmatrix} \\ &= \begin{bmatrix} (1)(1)+(0)(2)+(5)(0) & (1)(3)+(0)(0)+(5)(1) \\ (1)(1)+(2)(2)+(0)(0) & (1)(3)+(2)(0)+(0)(1) \end{bmatrix} \\ &= \begin{bmatrix} 1 & 8 \\ 5 & 3 \end{bmatrix}. \end{aligned} \]

The reversal of order is essential for the inner dimensions to remain compatible.

Algorithm: Given an \(m \times n\) matrix \(\mathbf{A}\) and an \(n \times p\) matrix \(\mathbf{B}\), the algorithm to compute the \(m \times p\) matrix \(\mathbf{C} = \mathbf{A}\mathbf{B}\) is as follows:

  • Create a new \(m \times p\) matrix, \(\mathbf{C}\), and fill it with zeros.
  • For each row index \(i\) from 1 to \(m\):
  • For each column index \(j\) from 1 to \(p\):
  • Initialize a running sum for the element \(C_{ij}\) to zero. Then, for each inner dimension index \(k\) from 1 to \(n\):
    • Multiply the corresponding elements: \(A_{ik} \times B_{kj}\).
    • Add the result to the running sum for \(C_{ij}\).
  • After the inner loop (over \(k\)) completes, the running sum is the final value for \(C_{ij}\).
  • Repeat until all elements of \(\mathbf{C}\) are computed.
  • Return the completed matrix \(\mathbf{C}\).

Complexity: To compute each of the \(mp\) entries of \(\mathbf{C}\), we perform an inner product of length \(n\), which costs \(2n-1\) FLOPs. The total cost is \(mp(2n-1)\) FLOPs. The complexity is therefore \(O(mnp)\). If \(n = p = m\), this is \(O(p^3)\). This cubic dependency makes matrix multiplication one of the more computationally demanding operations in machine learning.

Example 3.18 (Order of Operations Matters). The associative property ensures that for a product of three matrices, \((\mathbf{A}\mathbf{B})\mathbf{C} = \mathbf{A}(\mathbf{B}\mathbf{C})\). However, the number of floating-point operations (FLOPs) required for each computational path can be vastly different. The optimal strategy is to arrange the multiplications to keep the intermediate matrices as small as possible.

Let’s consider a scenario where we transform high-dimensional data into a low-dimensional space and then map it to an output space. This can be represented by a product of three matrices. Let’s define three matrices with the following dimensions:

  • \(\mathbf{A} \in \mathbb{R}^{10 \times 1000}\): A fat and short matrix, perhaps representing a mapping from a 1000-dimensional feature space down to 10 dimensions.
  • \(\mathbf{B} \in \mathbb{R}^{1000 \times 5}\): A very tall and thin matrix, like a “bottleneck” layer.
  • \(\mathbf{C} \in \mathbb{R}^{5 \times 50}\): A fat and short matrix, mapping the 50-dimensional space to a 5-dimensional space.

Our goal is to compute the final \(10 \times 50\) matrix, \(\mathbf{D} = \mathbf{A}\mathbf{B}\mathbf{C}\). We will compare the cost of the two possible orders of multiplication.

Case 1: The Efficient Order, \((\mathbf{A}\mathbf{B})\mathbf{C}\): First, we compute the intermediate matrix \(\mathbf{M}_1 = \mathbf{A}\mathbf{B}\).

  • Operation: \(\underset{10 \times 1000}{\mathbf{A}} \times \underset{1000 \times 5}{\mathbf{B}}\)
  • Resulting Matrix Size: \(\mathbf{M}_1\) will have dimensions \(10 \times 5\).
  • Multiplications: Using the \(O(mnp)\) formula, the cost is \(m \times n \times p = 10 \times 1000 \times 5 = 50,000\) multiplications (each product also needs nearly as many additions, so its FLOP count, \(mp(2n-1)\), is about twice this; the comparison is the same).

Next, we multiply this small intermediate matrix by \(\mathbf{C}\) to get the final result.

  • Operation: \(\underset{10 \times 5}{\mathbf{M}_1} \times \underset{5 \times 50}{\mathbf{C}}\)
  • Resulting Matrix Size: The final matrix will have dimensions \(10 \times 50\).
  • Multiplications: The cost is \(10 \times 5 \times 50 = 2,500\) multiplications.

Total Cost for Case 1: \(50,000 + 2,500 = \text{52,500 multiplications}\). This order is efficient because the very first multiplication collapses the largest dimension (1000), resulting in a tiny intermediate matrix.

Case 2: The Inefficient Order, \(\mathbf{A}(\mathbf{B}\mathbf{C})\): First, we compute the intermediate matrix \(\mathbf{M}_2 = \mathbf{B}\mathbf{C}\).

  • Operation: \(\underset{1000 \times 5}{\mathbf{B}} \times \underset{5 \times 50}{\mathbf{C}}\)
  • Resulting Matrix Size: \(\mathbf{M}_2\) will have dimensions \(1000 \times 50\).
  • Multiplications: The cost is \(1000 \times 5 \times 50 = 250,000\) multiplications.

Next, we pre-multiply this large intermediate matrix by \(\mathbf{A}\).

  • Operation: \(\underset{10 \times 1000}{\mathbf{A}} \times \underset{1000 \times 50}{\mathbf{M}_2}\)
  • Resulting Matrix Size: The final matrix will have dimensions \(10 \times 50\).
  • Multiplications: The cost is \(10 \times 1000 \times 50 = 500,000\) multiplications.

Total Cost for Case 2: \(250,000 + 500,000 = \text{750,000 multiplications}\). This order is inefficient because the first multiplication creates a large intermediate matrix, which then makes the second multiplication very expensive.

Order of OperationsMultiplications
\((\mathbf{A}\mathbf{B})\mathbf{C}\) (Efficient)52,500
\(\mathbf{A}(\mathbf{B}\mathbf{C})\) (Inefficient)750,000

Both methods produce the exact same final \(10 \times 50\) matrix, but the inefficient order of operations requires nearly 15 times more computation. This difference highlights a critical lesson: the mathematical structure of a problem (like associativity) provides choices, and making the right choice based on computational complexity can lead to performance gains. This is the core idea behind the “matrix chain multiplication” problem in algorithm design, which uses dynamic programming to find the optimal order of multiplications for a long chain of matrices.

Code session · Example 3.18 Skip to Section 3.5

Same product, two orders

Example 3.18's three matrices, of sizes 10 x 1000, 1000 x 5 and 5 x 50, multiplied in both orders and timed.

show setup
import numpy as np
import timeit
1rng = np.random.default_rng(0)
2A = rng.normal(size=(10, 1000))
3B = rng.normal(size=(1000, 5))
4C = rng.normal(size=(5, 50))
5mults = {"(AB)C": 10 * 1000 * 5 + 10 * 5 * 50, "A(BC)": 1000 * 5 * 50 + 10 * 1000 * 50}
6runs = {"(AB)C": lambda: (A @ B) @ C, "A(BC)": lambda: A @ (B @ C)}
7times = {}
8for name, run in runs.items():
9    times[name] = min(timeit.repeat(run, number=2000, repeat=7)) / 2000 * 1e6   # microseconds
10    print(f"{name}: {mults[name]:>7,} multiplications, {times[name]:6.1f} microseconds")
11print("same matrix:", np.allclose((A @ B) @ C, A @ (B @ C)))
Recorded output
(AB)C:  52,500 multiplications,    5.5 microseconds
A(BC): 750,000 multiplications,   34.9 microseconds
same matrix: True
Multiplications 0 300k 600k 900k 52,500 (AB)C 750,000 A(BC) 14× multiplications Time (microseconds) 0 15 30 45 5.45 µs (AB)C 34.95 µs A(BC) 6.4× runtime

Both orders give the same 10 x 50 matrix. A(BC) does 14 times as many multiplications as (AB)C and takes about 6 times as long on this laptop. The big products run faster per multiplication than the small ones, so time grows more slowly than the count; the order still decides the cost.

Recorded on an Apple M1 Max laptop, macOS 26.6.2, Python 3.13.7, NumPy 2.4.6, 2026-11-30.

3.5 Interlude: A Deeper Look at Matrix Multiplication

Thus far, we have defined matrix multiplication through its element-wise formula, which naturally leads to an algorithm with three nested loops. In this interlude, we will explore a more abstract and powerful perspective by viewing matrix multiplication through the lens of divide-and-conquer, a cornerstone of computer science algorithms. This approach will not only provide a rigorous proof of its correctness using induction on block matrices but will also allow us to analyze its computational complexity using the Master Theorem.

3.5.1 The Divide-and-Conquer View: Block Matrix Multiplication

The core idea is to break down a large problem into smaller, self-similar subproblems, solve them recursively, and then combine their results. For matrix multiplication, this means partitioning our matrices into smaller sub-matrices, called blocks.

For simplicity, let’s consider two \(n \times n\) matrices \(\mathbf{A}\) and \(\mathbf{B}\) where \(n\) is a power of 2. We can split each matrix into four blocks of size \(\frac{n}{2} \times \frac{n}{2}\):

\[ \mathbf{A} = \begin{bmatrix} \mathbf{A}_{11} & \mathbf{A}_{12} \\ \mathbf{A}_{21} & \mathbf{A}_{22} \end{bmatrix}, \quad \mathbf{B} = \begin{bmatrix} \mathbf{B}_{11} & \mathbf{B}_{12} \\ \mathbf{B}_{21} & \mathbf{B}_{22} \end{bmatrix}. \]

The product \(\mathbf{C} = \mathbf{A}\mathbf{B}\) can also be partitioned into four corresponding blocks:

\[ \mathbf{C} = \begin{bmatrix} \mathbf{C}_{11} & \mathbf{C}_{12} \\ \mathbf{C}_{21} & \mathbf{C}_{22} \end{bmatrix}. \]

Remarkably, the formulas for computing the blocks of \(\mathbf{C}\) look exactly like the standard multiplication of \(2 \times 2\) scalar matrices, but with matrix operations (multiplication and addition) instead of scalar ones:

\[ \begin{aligned} \mathbf{C}_{11} &= \mathbf{A}_{11}\mathbf{B}_{11} + \mathbf{A}_{12}\mathbf{B}_{21} \\ \mathbf{C}_{12} &= \mathbf{A}_{11}\mathbf{B}_{12} + \mathbf{A}_{12}\mathbf{B}_{22} \\ \mathbf{C}_{21} &= \mathbf{A}_{21}\mathbf{B}_{11} + \mathbf{A}_{22}\mathbf{B}_{21} \\ \mathbf{C}_{22} &= \mathbf{A}_{21}\mathbf{B}_{12} + \mathbf{A}_{22}\mathbf{B}_{22} \end{aligned} \]

This suggests a recursive algorithm: to multiply two \(n \times n\) matrices, we perform 8 multiplications and 4 additions of \(\frac{n}{2} \times \frac{n}{2}\) matrices. But first, let’s prove that this block-wise method is mathematically correct.

Theorem 3.1. The block matrix multiplication formula is equivalent to the standard element-wise definition of matrix multiplication.

We will prove this by induction on the size of the matrix, \(n\). We assume \(n\) is a power of 2.

Base Case: Let \(n=2\). In this case, each block \(\mathbf{A}_{ij}, \mathbf{B}_{ij}\) is a \(1 \times 1\) matrix (a scalar). Let’s write them as \(a_{ij}, b_{ij}\). The block formula for the top-left element \(C_{11}\) becomes:

\[ C_{11} = A_{11}B_{11} + A_{12}B_{21} = a_{11}b_{11} + a_{12}b_{21}. \]

This is exactly the standard definition for the element \(C_{11}\) of a \(2 \times 2\) matrix product. The same holds true for \(C_{12}, C_{21}, C_{22}\). Thus, the theorem holds for the base case.

Inductive Hypothesis: Assume that the block multiplication formula is correct for any pair of square matrices of size \(k \times k\), where \(k = n/2\).

Inductive Step: We must show that the formula is correct for an \(n \times n\) matrix. Let’s prove that an arbitrary element \(C_{ij}\) is computed correctly. We will consider an element in the top-left block \(\mathbf{C}_{11}\), meaning \(1 \le i, j \le n/2\).

According to the block formula, the \((i,j)\)-th element of \(\mathbf{C}_{11}\) is:

\[ (\mathbf{C}_{11})_{ij} = (\mathbf{A}_{11}\mathbf{B}_{11} + \mathbf{A}_{12}\mathbf{B}_{21})_{ij} = (\mathbf{A}_{11}\mathbf{B}_{11})_{ij} + (\mathbf{A}_{12}\mathbf{B}_{21})_{ij}. \]

By our inductive hypothesis, since \(\mathbf{A}_{11}, \mathbf{B}_{11}, \dots\) are all \(\frac{n}{2} \times \frac{n}{2}\) matrices, we can use the standard summation formula for their products:

\[ \begin{aligned} (\mathbf{A}_{11}\mathbf{B}_{11})_{ij} &= \sum_{k=1}^{n/2} (\mathbf{A}_{11})_{ik} (\mathbf{B}_{11})_{kj} \\(\mathbf{A}_{12}\mathbf{B}_{21})_{ij} &= \sum_{k=1}^{n/2} (\mathbf{A}_{12})_{ik} (\mathbf{B}_{21})_{kj}. \end{aligned} \]

Now, we relate the indices of the blocks to the indices of the original matrices \(\mathbf{A}\) and \(\mathbf{B}\):

  • \((\mathbf{A}_{11})_{ik} = A_{i,k}\)
  • \((\mathbf{B}_{11})_{kj} = B_{k,j}\)
  • \((\mathbf{A}_{12})_{ik} = A_{i, k+n/2}\)
  • \((\mathbf{B}_{21})_{kj} = B_{k+n/2, j}\)

Substituting these back into our expression for \((\mathbf{C}_{11})_{ij}\):

\[ (\mathbf{C}_{11})_{ij} = \sum_{k=1}^{n/2} A_{i,k} B_{k,j} + \sum_{k=1}^{n/2} A_{i, k+n/2} B_{k+n/2, j}. \]

Let’s re-index the second summation. Let \(k' = k+n/2\). As \(k\) goes from \(1\) to \(n/2\), \(k'\) goes from \(n/2+1\) to \(n\).

\[ (\mathbf{C}_{11})_{ij} = \sum_{k=1}^{n/2} A_{ik} B_{kj} + \sum_{k'=n/2+1}^{n} A_{ik'} B_{k'j}. \]

Combining these two sums gives a single summation over the full inner dimension \(n\):

\[ (\mathbf{C}_{11})_{ij} = \sum_{k=1}^{n} A_{ik} B_{kj}. \]

This is precisely the standard definition for the element \(C_{ij}\) in the final matrix. A similar argument holds for elements in the other three blocks (\(\mathbf{C}_{12}, \mathbf{C}_{21}, \mathbf{C}_{22}\)), which completes the proof.

3.5.2 Complexity Analysis via the Master Theorem

Now that we have established that the recursive block algorithm is correct, we can analyze its computational complexity. Let \(T(n)\) be the number of FLOPs required to multiply two \(n \times n\) matrices.

  • Divide: Splitting the matrices into blocks costs no FLOPs.
  • Conquer: We recursively solve 8 subproblems, each involving the multiplication of \(\frac{n}{2} \times \frac{n}{2}\) matrices. The cost for this is \(8 \cdot T(n/2)\).
  • Combine: We perform 4 additions of \(\frac{n}{2} \times \frac{n}{2}\) matrices. Each addition costs \((\frac{n}{2})^2 = \frac{n^2}{4}\) FLOPs. The total combination cost is \(4 \cdot \frac{n^2}{4} = n^2\) FLOPs.

This gives us the recurrence relation for the complexity:

\[ T(n) = 8T(n/2) + \Theta(n^2). \]

This recurrence is a perfect candidate for analysis using the Master Theorem.

Lemma 3.2 (Master Theorem for Divide-and-Conquer Recurrences). Given a recurrence of the form \(T(n) = aT(n/b) + f(n)\), where \(a \ge 1, b > 1\):

  1. If \(f(n) = O(n^{\log_b a - \epsilon})\) for some \(\epsilon > 0\), then \(T(n) = \Theta(n^{\log_b a})\).
  2. If \(f(n) = \Theta(n^{\log_b a})\), then \(T(n) = \Theta(n^{\log_b a} \log n)\).
  3. If \(f(n) = \Omega(n^{\log_b a + \epsilon})\) for some \(\epsilon > 0\), and if \(af(n/b) \le cf(n)\) for \(c<1\) and sufficiently large \(n\), then \(T(n) = \Theta(f(n))\).

For our recurrence \(T(n) = 8T(n/2) + \Theta(n^2)\), we have:

  • \(a = 8\) (the number of recursive calls)
  • \(b = 2\) (the factor by which the input size is reduced)
  • \(f(n) = \Theta(n^2)\) (the cost of the “combine” step)

We need to compare \(f(n)\) with the term \(n^{\log_b a}\). Let’s compute the exponent:

\[ \log_b a = \log_2 8 = 3. \]

So, we are comparing \(f(n) = \Theta(n^2)\) with \(n^3\).

Since \(n^2 = O(n^{3 - \epsilon})\) for \(\epsilon = 1\), our recurrence falls squarely into Case 1 of the Master Theorem.

The theorem tells us that the complexity is dominated by the recursive calls, and the solution is:

\[ T(n) = \Theta(n^{\log_b a}) = \Theta(n^3). \]

This analysis formally proves that the naive divide-and-conquer algorithm for matrix multiplication has a cubic time complexity, the same as the iterative three-loop algorithm. It might seem like a lot of work for the same result, but this perspective is what opened the door to faster algorithms. In 1969, Volker Strassen realized that the block multiplications could be cleverly rearranged to require only 7 recursive calls instead of 8, at the cost of more additions. This leads to the recurrence \(T(n) = 7T(n/2) + \Theta(n^2)\). Applying the Master Theorem to this gives a complexity of \(\Theta(n^{\log_2 7}) \approx \Theta(n^{2.807})\), which was the first algorithm to break the \(O(n^3)\) barrier.

3.5.3 Matrix-Matrix Multiplication at the Heart of Modern AI

While the inner product allows us to compare two vectors, matrix-matrix multiplication scales this up dramatically, enabling the comparison of an entire set of vectors against another set in a single, highly optimized operation. This ability to perform computations in large batches is the engine that drives the performance of modern AI systems. The seemingly complex \(O(mnp)\) cost of this operation is a price willingly paid for the parallelism it unlocks. Let’s see how this powers some of the most advanced AI architectures.

Example 3.19 (Matrix Factorization: Predicting All Ratings at Once). In the vector example, we saw how the inner product \(\mathbf{p}_u^\top \mathbf{q}_i\) could predict a single rating for user \(u\) on movie \(i\). But a real-world recommendation system needs to reason about billions of users and millions of movies/tv-series. Matrix-matrix multiplication allows us to compute all possible predicted ratings in one go. The system learns two smaller, “latent feature” matrices:

  • A user-feature matrix \(\mathbf{P} \in \mathbb{R}^{m \times k}\), where each of the \(m\) rows is a \(k\)-dimensional vector representing a user’s tastes.
  • A movie-feature matrix \(\mathbf{Q} \in \mathbb{R}^{n \times k}\), where each of the \(n\) rows is a \(k\)-dimensional vector representing a movie’s characteristics.

To get all \(m \times n\) rating predictions, we multiply the user-feature matrix \(\mathbf{P}\) by the transpose of the movie-feature matrix, \(\mathbf{Q}^\top\). The element at the \(i\)-th row and \(j\)-th column of the resulting matrix is the inner product of the \(i\)-th user’s vector with the \(j\)-th movie’s vector.

\[ \underbrace{\widehat{\mathbf{R}}}_{m \times n} = \underbrace{\mathbf{P}}_{m \times k} \cdot \underbrace{\mathbf{Q}^\top}_{k \times n} \] \[ \begin{bmatrix} \hat{r}_{11} & \cdots & \hat{r}_{1n} \\ \vdots & \ddots & \vdots \\ \hat{r}_{m1} & \cdots & \hat{r}_{mn} \end{bmatrix} = \begin{bmatrix} \text{--- user}_1 \text{ ---} \\ \vdots \\ \text{--- user}_m \text{ ---} \end{bmatrix} \begin{bmatrix} | & & | \\ \text{movie}_1 & \cdots & \text{movie}_n \\ | & & | \end{bmatrix} \]

This single matrix multiplication generates the complete matrix of predicted ratings. The optimization task is then to find the matrices \(\mathbf{P}\) and \(\mathbf{Q}\) such that their product \(\mathbf{P}\mathbf{Q}^\top\) is as close as possible to the matrix of known ratings.

Example 3.20 (Attention Mechanisms). The vector example showed how an inner product could compute an “attention score” between a single “query” word and a single “key” word. The mechanism that powers Large Language Models (LLMs) like ChatGPT needs to do this for every word in a sentence against every other word, all at once. This is a perfect job for matrix-matrix multiplication.

For a sentence with \(s\) words, the model generates three matrices from the input word embeddings:

  • A Query matrix \(\mathbf{Q} \in \mathbb{R}^{s \times d}\), where each row is the “query” vector for a word asking, “Who should I pay attention to?”
  • A Key matrix \(\mathbf{K} \in \mathbb{R}^{s \times d}\), where each row is the “key” vector for a word answering, “Here is the information I have.”
  • A Value matrix \(\mathbf{V} \in \mathbb{R}^{s \times d}\), where each row is the “value” vector representing the actual content of a word.

The attention scores are computed by multiplying the Query matrix by the transpose of the Key matrix. The resulting \(s \times s\) matrix contains all pairwise similarity scores between every word in the sentence.

\[ \underbrace{\mathbf{Scores}}_{s \times s} = \underbrace{\mathbf{Q}}_{s \times d} \cdot \underbrace{\mathbf{K}^\top}_{d \times s} \]

The element \((\mathbf{Scores})_{ij}\) is the inner product of the query from word \(i\) and the key from word \(j\), representing how much word \(i\) should attend to word \(j\). These scores are then normalized (typically using a softmax function) and multiplied by the Value matrix \(\mathbf{V}\) to produce the final output. The core of this entire mechanism is a single, powerful matrix multiplication that computes \(s^2\) alignment scores in parallel.

Example 3.21 (Convolution). Convolutional Neural Networks, used for image recognition, are typically understood as sliding a small filter (a kernel) across an image. While this is conceptually intuitive, it is computationally inefficient. Modern deep learning libraries achieve speedups by cleverly reformulating this sliding process as a single, large matrix-matrix multiplication, a technique often called im2col (image-to-column).

Imagine a small \(3 \times 3\) kernel that slides over an image.

  1. Kernel Matrix: All the kernels (or filters) are unrolled from their 2D shape into rows of a single, large kernel matrix \(\mathbf{W}_{\text{flat}}\).
  2. Image Patch Matrix: The im2col operation extracts every single image patch that the kernel would slide over. Each patch is unrolled into a column. These columns are then stacked side-by-side to form a huge intermediate image patch matrix \(\mathbf{X}_{\text{col}}\). The number of rows in this matrix matches the number of columns in the kernel matrix.

The entire convolution operation, which involves thousands of sliding inner products, is now reduced to one matrix-matrix multiplication:

\[ \underbrace{\mathbf{Y}_{\text{flat}}}_{\text{Output Features}} = \underbrace{\mathbf{W}_{\text{flat}}}_{\text{Filters}} \cdot \underbrace{\mathbf{X}_{\text{col}}}_{\text{Image Patches}} \]

The resulting output matrix \(\mathbf{Y}_{\text{flat}}\) contains the output of the convolutional layer in a flattened form, which is then reshaped back into its proper 2D spatial arrangement. By converting convolution into this form, deep learning frameworks can leverage highly optimized matrix multiplication routines (like BLAS and cuBLAS on GPUs) that are the fastest numerical operations available on modern hardware. This transformation is one of the key reasons why CNNs can be trained so efficiently.

3.5.4 The Inner Product of Matrices

The concept of an inner product can be extended from vectors to matrices. The inner product of two matrices \(\mathbf{A}, \mathbf{B} \in \mathbb{R}^{m \times p}\) is a scalar defined as the sum of the element-wise products of their entries. It can be computed elegantly using the trace operator, \(\text{Tr}(\cdot)\), which sums the diagonal elements of a square matrix:

\[ \langle \mathbf{A}, \mathbf{B} \rangle = \sum_{i=1}^m \sum_{j=1}^p A_{ij} B_{ij} = \text{Tr}(\mathbf{A}^\top \mathbf{B}). \]

This definition reveals a powerful connection: the inner product of two matrices is identical to the inner product of their vectorized forms, i.e., \(\langle \text{vec}(\mathbf{A}), \text{vec}(\mathbf{B}) \rangle\). Check it!

  • Properties: The matrix inner product inherits all the properties of the vector one: it is commutative, distributive, and bilinear.
  • Complexity: This operation requires \(mp\) multiplications and \(mp-1\) additions. The complexity is \(O(mp)\).

3.5.5 The Outer Product of Vectors

The outer product of an \(m\)-vector \(\mathbf{x}\) and a \(p\)-vector \(\mathbf{y}\) is the \(m \times p\) matrix \(\mathbf{A} = \mathbf{x}\mathbf{y}^\top\), where \(A_{ij} = x_i y_j\).

  • Complexity: This requires \(mp\) multiplications. The complexity is \(O(mp)\).

Outer products of non-zero vectors create rank-one matrices (more about rank of a matrix later in the class) and are fundamental in many algorithms, including the update rules in some optimization methods and the decomposition of matrices.

3.6 Functions of Matrices

Just as we defined scalar-valued functions of vectors, we can define functions that take a matrix as input and produce a single scalar output. In AI, these are often cost or loss functions that measure how well a matrix of model parameters, \(\mathbf{W}\), performs on a given task. The principles of optimization remain the same, but our variable now lives in a higher-dimensional matrix space.

3.6.1 Example: Multivariate Linear Regression

A powerful generalization of the least-squares problem is multivariate or multi-target linear regression. Instead of predicting a single outcome, we want to predict multiple outcomes simultaneously.

Imagine we want to predict not just the price of a house, but also its expected time on the market and a “desirability” score. For each of the \(n\) houses in our dataset, we have an input feature vector \(\mathbf{x}_i \in \mathbb{R}^p\). Our target is now a vector of \(d\) outcomes, \(\mathbf{y}_i \in \mathbb{R}^d\).

The Model. Our model must now map a \(p\)-dimensional input to a \(d\)-dimensional output. A linear model can achieve this using a weight matrix \(\mathbf{W} \in \mathbb{R}^{p \times d}\). The prediction for the \(i\)-th data point is a vector:

\[ \hat{\mathbf{y}}_i = \mathbf{W}^\top \mathbf{x}_i \quad (\text{so as a row vector, } \hat{\mathbf{y}}_i^\top = \mathbf{x}_i^\top \mathbf{W}). \]

Here, the \(j\)-th element of our prediction, \((\hat{\mathbf{y}}_i)_j\), is the inner product of the feature vector \(\mathbf{x}_i\) with the \(j\)-th column of the weight matrix, \(\mathbf{w}_{:,j}\). Each column of \(\mathbf{W}\) can be thought of as a separate regression model for one of the \(d\) outcomes.

The Cost Function. Our goal is to find the single weight matrix \(\mathbf{W}\) that minimizes the error across all data points and across all prediction targets. We can define the error as the sum of squared differences between every predicted element and every true element.

Let’s define a residual matrix \(\mathbf{R} = \mathbf{Y} - \mathbf{X}\mathbf{W}\), where \(\mathbf{X}\) is the \(n \times p\) matrix of input features (each row is an \(\mathbf{x}_i^\top\)) and \(\mathbf{Y}\) is the \(n \times d\) matrix of true outcomes. The element \(R_{ij}\) is the error for the \(j\)-th outcome of the \(i\)-th data point. The total cost is the sum of the squares of all elements in this residual matrix:

\[ f(\mathbf{W}) = \sum_{i=1}^n \sum_{j=1}^d R_{ij}^2 = \sum_{i=1}^n \sum_{j=1}^d \left( Y_{ij} - (\mathbf{XW})_{ij} \right)^2. \]

Expanding the term \((\mathbf{XW})_{ij}\), which is the inner product of the \(i\)-th row of \(\mathbf{X}\) and the \(j\)-th column of \(\mathbf{W}\), gives:

\[ f(\mathbf{W}) = \sum_{i=1}^n \sum_{j=1}^d \left( Y_{ij} - \sum_{k=1}^p X_{ik}W_{kj} \right)^2. \]

This is a quadratic function of the elements of \(\mathbf{W}\). The optimization problem is to find the matrix \(\mathbf{W}^\star\) that minimizes this cost:

\[ \min_{\mathbf{W} \in \mathbb{R}^{p \times d}} f(\mathbf{W}). \]

3.6.2 Taylor Approximation for Matrix Functions

To develop an iterative algorithm like gradient descent, we need to understand how a function \(f(\mathbf{W})\) changes when we make a small change to the matrix \(\mathbf{W}\). This requires generalizing the Taylor approximation to functions of matrices.

The first-order Taylor approximation for a function \(f: \mathbb{R}^{m \times p} \to \mathbb{R}\) around a point \(\mathbf{W}_0\) is a direct analogue of the vector case. It uses the gradient, which is now a matrix, and the matrix inner product.

Definition 3.1 (1st Taylor Approximation for Matrix Functions). The linear approximation of a differentiable function \(f(\mathbf{W})\) for a matrix \(\mathbf{W}\) near a point \(\mathbf{W}_0\) is given by:

\[ f(\mathbf{W}) \approx f(\mathbf{W}_0) + \langle \nabla f(\mathbf{W}_0), \mathbf{W} - \mathbf{W}_0 \rangle. \]

Here, \(\nabla f(\mathbf{W}_0)\) is the gradient of \(f\) evaluated at \(\mathbf{W}_0\). It is an \(m \times p\) matrix of the same dimensions as \(\mathbf{W}\). The inner product \(\langle \mathbf{A}, \mathbf{B} \rangle = \mathrm{Tr}(\mathbf{A}^\top \mathbf{B})\) is the matrix inner product.

3.6.3 The Gradient of a Matrix Function

For a function \(f\) that takes an \(m \times p\) matrix \(\mathbf{W}\) as input, its gradient, \(\nabla f(\mathbf{W})\), is also an \(m \times p\) matrix. Each element of the gradient matrix is the partial derivative of the function with respect to the corresponding element of \(\mathbf{W}\):

\[ (\nabla f(\mathbf{W}))_{ij} = \frac{\partial f}{\partial W_{ij}}. \]

The gradient matrix \(\nabla f(\mathbf{W})\) points in the direction of steepest ascent in the high-dimensional space of matrices.

Example 3.22 (Gradient of the Squared Sum). Let’s revisit the simple cost function \(f(\mathbf{W}) = \sum_{i=1}^m \sum_{j=1}^p W_{ij}^2\). To find its gradient, we compute the partial derivative with respect to an arbitrary element, say \(W_{kl}\).

\[ \frac{\partial f}{\partial W_{kl}} = \frac{\partial}{\partial W_{kl}} \left( \sum_{i=1}^m \sum_{j=1}^p W_{ij}^2 \right). \]

The derivative is zero for all terms in the sum where \((i,j) \neq (k,l)\). The only non-zero term is when we differentiate \(W_{kl}^2\):

\[ \frac{\partial f}{\partial W_{kl}} = \frac{\partial}{\partial W_{kl}} (W_{kl}^2) = 2W_{kl}. \]

Since this holds for any element \((k,l)\), the gradient matrix is:

\[ (\nabla f(\mathbf{W}))_{kl} = 2W_{kl} \quad \implies \quad \nabla f(\mathbf{W}) = 2\mathbf{W}. \]

This is a perfect analogue of the vector case where the gradient of \(\|\mathbf{x}\|_2^2\) is \(2\mathbf{x}\).

Example 3.23 (Gradient of a Linear Matrix Function). Consider the linear function \(f(\mathbf{W}) = \langle \mathbf{A}, \mathbf{W} \rangle = \sum_{i=1}^m \sum_{j=1}^p A_{ij}W_{ij}\). To find the gradient, we compute the partial derivative with respect to an arbitrary element \(W_{kl}\):

\[ \frac{\partial f}{\partial W_{kl}} = \frac{\partial}{\partial W_{kl}} \left( \sum_{i=1}^m \sum_{j=1}^p A_{ij}W_{ij} \right). \]

Again, the derivative is zero for all terms except where \((i,j) = (k,l)\):

\[ \frac{\partial f}{\partial W_{kl}} = \frac{\partial}{\partial W_{kl}} (A_{kl}W_{kl}) = A_{kl}. \]

Since this holds for any element, the gradient matrix is simply:

\[ (\nabla f(\mathbf{W}))_{kl} = A_{kl} \quad \implies \quad \nabla f(\mathbf{W}) = \mathbf{A}. \]

This is the matrix analogue of the fact that the gradient of \(\mathbf{a}^\top\mathbf{x}\) is \(\mathbf{a}\).

3.6.4 Gradient Descent for Matrix Functions

The logic of gradient descent remains unchanged. To minimize \(f(\mathbf{W})\), we start with an initial guess \(\mathbf{W}_0\) and iteratively take steps in the direction of the negative gradient.

Definition 3.2 (Gradient Descent for Matrices). Given a differentiable function \(f(\mathbf{W})\) and a starting matrix \(\mathbf{W}_0\), the gradient descent algorithm generates a sequence of matrices via the update rule:

\[ \mathbf{W}_{t+1} = \mathbf{W}_t - \eta \nabla f(\mathbf{W}_t), \]

for \(t = 0, 1, 2, \dots\). Here, \(\eta > 0\) is the learning rate, and the update involves a matrix subtraction.

Example 3.24 (On-Paper Gradient Descent with a 2x2 Matrix). Let’s find the matrix \(\mathbf{W}\) that minimizes its squared distance to a target matrix \(\mathbf{B}\).

  • Objective Function: \(f(\mathbf{W}) = \frac{1}{2} \sum_{i=1}^2 \sum_{j=1}^2 (W_{ij} - B_{ij})^2\).
  • Target Matrix: Let \(\mathbf{B} = \begin{bmatrix} 5 & 1 \\ 0 & 3 \end{bmatrix}\). The obvious minimum is at \(\mathbf{W}^\star = \mathbf{B}\).
  • Gradient: From our earlier examples, it can be shown that \(\nabla f(\mathbf{W}) = \mathbf{W} - \mathbf{B}\).

Let’s perform one step of gradient descent.

  • Starting Point: \(\mathbf{W}_0 = \begin{bmatrix} 0 & 0 \\ 0 & 0 \end{bmatrix}\).
  • Learning Rate: \(\eta = 0.5\).

Iteration 1:

  1. Calculate the Gradient at \(\mathbf{W}_0\): \[ \nabla f(\mathbf{W}_0) = \mathbf{W}_0 - \mathbf{B} = \begin{bmatrix} 0 & 0 \\ 0 & 0 \end{bmatrix} - \begin{bmatrix} 5 & 1 \\ 0 & 3 \end{bmatrix} = \begin{bmatrix} -5 & -1 \\ 0 & -3 \end{bmatrix}. \]
  2. Perform the Update: \[ \begin{aligned} \mathbf{W}_1 &= \mathbf{W}_0 - \eta \nabla f(\mathbf{W}_0) \\ &= \begin{bmatrix} 0 & 0 \\ 0 & 0 \end{bmatrix} - 0.5 \begin{bmatrix} -5 & -1 \\ 0 & -3 \end{bmatrix} \\ &= \begin{bmatrix} 0 & 0 \\ 0 & 0 \end{bmatrix} - \begin{bmatrix} -2.5 & -0.5 \\ 0 & -1.5 \end{bmatrix} \\ &= \begin{bmatrix} 2.5 & 0.5 \\ 0 & 1.5 \end{bmatrix}. \end{aligned} \]

After one step, our estimate \(\mathbf{W}_1\) has moved from the zero matrix to a matrix that is halfway to the target \(\mathbf{B}\). Subsequent iterations will continue to close this gap, with the update step size shrinking as \(\mathbf{W}_t\) gets closer to \(\mathbf{B}\) and the gradient \(\mathbf{W}_t - \mathbf{B}\) gets smaller. This simple example shows how the entire gradient descent framework seamlessly generalizes from vector variables to matrix variables.

3.7 Norms and Distances for Matrices

To formalize the notion of a matrix’s “size” or the “distance” between two matrices, we extend the concept of norms from vectors to matrices. This is not just a theoretical exercise; in machine learning, we constantly need to measure quantities like the magnitude of a neural network’s weight matrix (to prevent it from getting too large) or the magnitude of a prediction error matrix (which we aim to minimize). A function \(\|\cdot\|: \mathbb{R}^{m \times p} \to \mathbb{R}\) is a valid norm if it satisfies the same four axioms as vector norms for all matrices \(\mathbf{A}, \mathbf{B} \in \mathbb{R}^{m \times p}\) and any scalar \(\alpha \in \mathbb{R}\):

  1. Non-negativity: \(\|\mathbf{A}\| \ge 0\).
  2. Definiteness: \(\|\mathbf{A}\| = 0\) if and only if \(\mathbf{A} = \mathbf{0}\).
  3. Positive Homogeneity: \(\|\alpha\mathbf{A}\| = |\alpha|\|\mathbf{A}\|\).
  4. Triangle Inequality: \(\|\mathbf{A}+\mathbf{B}\| \le \|\mathbf{A}\| + \|\mathbf{B}\|\).

These axioms ensure that any matrix norm provides a consistent measure of magnitude. While many such norms exist, we will focus on the direct generalizations of the vector norms we have already seen.

3.7.1 The Frobenius Norm (Matrix \(\ell_2\)-norm but use \(\|\cdot\|_F\) to denote it)

The most direct and widely used matrix norm is the Frobenius norm, which is the matrix equivalent of the vector \(\ell_2\)-norm. It is defined as the square root of the sum of the squares of all its elements. If we were to “unroll” or “vectorize” the matrix into a single long vector of size \(mp\), its Frobenius norm would be identical to the \(\ell_2\)-norm of that vector. Its math form is:

\[ \|\mathbf{A}\|_F = \sqrt{\sum_{i=1}^m \sum_{j=1}^p A_{ij}^2} = \sqrt{\langle \mathbf{A}, \mathbf{A} \rangle} = \sqrt{\text{Tr}(\mathbf{A}^\top \mathbf{A})}. \]
  • Complexity Analysis: To compute the Frobenius norm, we must perform:
    • \(mp\) multiplications to square each element \(A_{ij}\).
    • \(mp-1\) additions to sum the squared elements.
    • 1 square root operation.

    The complexity is therefore \(O(mp)\).

3.7.2 The Element-wise \(\ell_1\)-norm

Analogous to the vector \(\ell_1\)-norm, this norm is the sum of the absolute values of all elements in the matrix. It is sometimes used in optimization problems to encourage sparsity (many zero elements) in a weight matrix.

\[ \|\mathbf{A}\|_1 = \sum_{i=1}^m \sum_{j=1}^p |A_{ij}|. \]
  • Complexity Analysis: Computing this norm requires:
    • \(mp\) absolute value operations.
    • \(mp-1\) additions.

    The total complexity is \(O(mp)\).

3.7.3 The Max Norm (Element-wise \(\ell_\infty\)-norm)

Analogous to the vector \(\ell_\infty\)-norm, the max norm of a matrix is simply the maximum absolute value among all of its elements. This norm is often used as a constraint in optimization to keep the magnitude of individual weights in a neural network from growing too large.

\[ \|\mathbf{A}\|_\infty = \max_{\substack{1 \le i \le m \\ 1 \le j \le p}} |A_{ij}|. \]
  • Complexity Analysis: Computing this norm requires:
    • \(mp\) absolute value operations.
    • \(mp-1\) comparisons to find the maximum element.

    The complexity is \(O(mp)\).

We note that there are (more rigorously) many matrix-induced norms in the literature, but for the purposes of this class, the above definitions suffice. In more advanced topics, one needs to be careful when reading research materials about matrix norm definitions and what they represent.

Example 3.25 (Matrix Norm Calculation). Let \(\mathbf{A} = \begin{bmatrix} 1 & -2 & 0 \\ 3 & -4 & 5 \end{bmatrix}\). Let’s compute its three element-wise norms.

  • Frobenius Norm: \[ \begin{aligned} \|\mathbf{A}\|_F &= \sqrt{1^2 + (-2)^2 + 0^2 + 3^2 + (-4)^2 + 5^2} \\ &= \sqrt{1 + 4 + 0 + 9 + 16 + 25} = \sqrt{55} \approx 7.416. \end{aligned} \]
  • \(\ell_1\)-norm: \(\|\mathbf{A}\|_1 = |1| + |-2| + |0| + |3| + |-4| + |5| = 1 + 2 + 0 + 3 + 4 + 5 = 15\).
  • Max Norm: \(\|\mathbf{A}\|_\infty = \max(|1|, |-2|, |0|, |3|, |-4|, |5|) = 5\).

3.7.4 Algebraic Properties of the Frobenius Norm

The identity \(\|\mathbf{A}\|_F^2 = \langle \mathbf{A}, \mathbf{A} \rangle\) is the critical bridge between the algebraic inner product and the geometric norm, just as it was for vectors. This allows us to generalize key algebraic properties to matrices.

Identity (Norm of a Sum): For any two matrices \(\mathbf{A}, \mathbf{B} \in \mathbb{R}^{m \times p}\),

\[ \|\mathbf{A} + \mathbf{B}\|_F^2 = \|\mathbf{A}\|_F^2 + 2\langle \mathbf{A}, \mathbf{B} \rangle + \|\mathbf{B}\|_F^2. \]

Proof. The proof is a direct application of the distributive and commutative properties of the matrix inner product, mirroring the vector case exactly.

\[ \begin{aligned} \|\mathbf{A} + \mathbf{B}\|_F^2 &= \langle \mathbf{A} + \mathbf{B}, \mathbf{A} + \mathbf{B} \rangle \\ &= \langle \mathbf{A}, \mathbf{A} + \mathbf{B} \rangle + \langle \mathbf{B}, \mathbf{A} + \mathbf{B} \rangle \quad (\text{Distributivity}) \\ &= \langle \mathbf{A}, \mathbf{A} \rangle + \langle \mathbf{A}, \mathbf{B} \rangle + \langle \mathbf{B}, \mathbf{A} \rangle + \langle \mathbf{B}, \mathbf{B} \rangle \quad (\text{Same}) \\ &= \|\mathbf{A}\|_F^2 + \langle \mathbf{A}, \mathbf{B} \rangle + \langle \mathbf{A}, \mathbf{B} \rangle + \|\mathbf{B}\|_F^2 \quad (\text{Commutativity}) \\ &= \|\mathbf{A}\|_F^2 + 2\langle \mathbf{A}, \mathbf{B} \rangle + \|\mathbf{B}\|_F^2. \quad \square \end{aligned} \]

3.7.5 Revisiting the Quadratic Example: Multivariate Regression

We can now use this more powerful notation to analyze the objective function for multivariate linear regression, revealing its underlying quadratic structure.

Example 3.26 (Least-Squares Matrix Objective). Consider the objective function \(f(\mathbf{W}) = \frac{1}{2} \|\mathbf{Y} - \mathbf{XW}\|_F^2\), where we seek to find the optimal weight matrix \(\mathbf{W}\). This is equivalent to the multivariate linear regression problem in the previous section! We can expand this using the identity for the squared norm of a difference, \(\|\mathbf{A}-\mathbf{B}\|_F^2 = \|\mathbf{A}\|_F^2 - 2\langle \mathbf{A},\mathbf{B} \rangle + \|\mathbf{B}\|_F^2\). Let \(\mathbf{A} = \mathbf{Y}\) and \(\mathbf{B} = \mathbf{XW}\).

\[ \begin{aligned} f(\mathbf{W}) &= \frac{1}{2} \left( \|\mathbf{Y}\|_F^2 - 2\langle \mathbf{Y}, \mathbf{XW} \rangle + \|\mathbf{XW}\|_F^2 \right) \\ &= \frac{1}{2}\|\mathbf{Y}\|_F^2 - \langle \mathbf{Y}, \mathbf{XW} \rangle + \frac{1}{2}\|\mathbf{XW}\|_F^2. \end{aligned} \]

This expression neatly separates the objective into three parts:

  1. A constant term, \(\frac{1}{2}\|\mathbf{Y}\|_F^2\), which does not depend on our variable \(\mathbf{W}\).
  2. A linear term in \(\mathbf{W}\), given by the inner product \(-\langle \mathbf{Y}, \mathbf{XW} \rangle\).
  3. A quadratic term in \(\mathbf{W}\), given by \(\frac{1}{2}\|\mathbf{XW}\|_F^2\).

This confirms that the least-squares objective is a quadratic function of the matrix variable \(\mathbf{W}\). This structure is fundamental and guarantees that (under certain conditions on \(\mathbf{X}\)) the function has a single global minimum, making it a well-behaved optimization problem.

3.7.6 Fundamental Inequalities for Matrices

The core geometric inequalities that govern vector spaces extend directly to matrix spaces when using the Frobenius norm and its associated inner product.

Lemma 3.3 (Cauchy-Schwarz Inequality for Matrices). For any two matrices \(\mathbf{A}, \mathbf{B} \in \mathbb{R}^{m \times p}\), the following holds:

\[ |\langle \mathbf{A}, \mathbf{B} \rangle| \le \|\mathbf{A}\|_F \|\mathbf{B}\|_F. \]

The proof follows by recognizing that both the matrix inner product and the Frobenius norm are equivalent to the standard vector operations on the “vectorized” form of the matrices. Let \(\text{vec}(\mathbf{A})\) be the \(mp \times 1\) vector formed by stacking the columns of \(\mathbf{A}\). By definition:

  • \(\langle \mathbf{A}, \mathbf{B} \rangle = \sum_{i,j} A_{ij}B_{ij} = \langle \text{vec}(\mathbf{A}), \text{vec}(\mathbf{B}) \rangle\).
  • \(\|\mathbf{A}\|_F = \sqrt{\sum_{i,j} A_{ij}^2} = \|\text{vec}(\mathbf{A})\|_2\).

Applying the proven Cauchy-Schwarz inequality for vectors to \(\text{vec}(\mathbf{A})\) and \(\text{vec}(\mathbf{B})\):

\[ |\langle \text{vec}(\mathbf{A}), \text{vec}(\mathbf{B}) \rangle| \le \|\text{vec}(\mathbf{A})\|_2 \|\text{vec}(\mathbf{B})\|_2. \]

Substituting the matrix equivalents back in yields the desired result.  \(\square\)

Lemma 3.4 (Triangle Inequality for Matrices). For any two matrices \(\mathbf{A}, \mathbf{B} \in \mathbb{R}^{m \times p}\), the following holds:

\[ \|\mathbf{A} + \mathbf{B}\|_F \le \|\mathbf{A}\|_F + \|\mathbf{B}\|_F. \]

The proof is identical to the vector case, relying on the matrix Cauchy-Schwarz inequality. We start by expanding the squared norm of the sum:

\[ \begin{aligned} \|\mathbf{A}+\mathbf{B}\|_F^2 &= \|\mathbf{A}\|_F^2 + 2\langle \mathbf{A}, \mathbf{B} \rangle + \|\mathbf{B}\|_F^2 \\ &\le \|\mathbf{A}\|_F^2 + 2|\langle \mathbf{A}, \mathbf{B} \rangle| + \|\mathbf{B}\|_F^2 \quad (\text{since } z \le |z|) \\ &\le \|\mathbf{A}\|_F^2 + 2\|\mathbf{A}\|_F \|\mathbf{B}\|_F + \|\mathbf{B}\|_F^2 \quad (\text{by Cauchy-Schwarz}) \\ &= (\|\mathbf{A}\|_F + \|\mathbf{B}\|_F)^2. \end{aligned} \]

Taking the square root of both sides gives the triangle inequality.  \(\square\)

3.7.7 Distance and Angle Between Matrices

The Frobenius norm allows us to define the distance between two matrices \(\mathbf{A}\) and \(\mathbf{B}\) as the norm of their difference: \(\text{dist}(\mathbf{A}, \mathbf{B}) = \|\mathbf{A}-\mathbf{B}\|_F\). This is a crucial quantity in optimization, often forming the basis of a loss function (e.g., finding a matrix \(\mathbf{W}\) that minimizes its distance to a target matrix \(\mathbf{Y}\)).

Similarly, the angle \(\theta\) between two non-zero matrices is defined via their inner product and norms:

\[ \theta = \arccos\left(\frac{\langle \mathbf{A}, \mathbf{B} \rangle}{\|\mathbf{A}\|_F \|\mathbf{B}\|_F}\right). \]

This provides a measure of “similarity” or “alignment” between two matrices, a concept useful in comparing, for instance, the weight matrices of different layers in a neural network or different learned representations of data.

3.8 Beyond Matrices: A Glimpse at Tensors

Throughout this chapter we have written matrices as 2-dimensional arrays of numbers. The natural generalization, a \(k\)-dimensional array of numbers, is called a tensor.2

The data of modern AI is naturally tensorial. A grayscale image of size \(H \times W\) is a rank-2 tensor (a matrix). A batch of \(B\) such images is a rank-3 tensor of shape \((B, H, W)\). An RGB image is rank-3 (\((C, H, W)\) with \(C=3\)), and a batch of RGB images is rank-4: \((B, C, H, W)\). A sequence of \(T\) token embeddings each of dimension \(D\), batched across \(B\) examples, is rank-3: \((B, T, D)\). Matrices alone cannot express these shapes without awkward flattening.

3.8.1 Definitions: Rank, Axis, Shape

A rank-\(k\) tensor \(\mathcal{T}\) is an indexed collection of numbers with \(k\) indices: \(\mathcal{T}_{i_1 i_2 \cdots i_k}\). The number \(k\) is the tensor’s rank (also called its order or number of axes); the tuple of index ranges is its shape. The total number of entries is the product of the shape. We adopt the same bracket notation we have used for vectors and matrices, generalized to as many indices as needed.

A note on terminology: do not confuse tensor rank (the number of axes) with matrix rank (the number of linearly independent rows or columns), which is a property of a rank-2 tensor and does not generalize trivially to higher rank.

Example 3.27 (A small rank-3 tensor). The vector \(\mathbf{v} = [0,1,2,3,4,5,6,7,8,9,10,11]^\top \in \mathbb{R}^{12}\) can be reshaped into a \(3 \times 4\) matrix (rank-2 tensor) or further into a \(2 \times 2 \times 3\) rank-3 tensor without copying any data: the underlying buffer of 12 numbers is unchanged. The new shape is the new tuple \((2,2,3)\); the new strides are \((6,3,1)\), so index \((1,0,2)\) resolves to flat offset \(1\cdot 6 + 0\cdot 3 + 2 = 8\), holding value \(8\). Reshape is therefore an \(O(1)\) metadata operation: only the shape and stride tuples change.

3.8.2 The Three Operations that Matter

For optimization purposes, the operations on tensors that we encounter most often generalize three operations already familiar from this chapter:

Element-wise operations and broadcasting. Adding two tensors of the same shape adds them position by position, at a cost of one FLOP per element. The more interesting case is when shapes differ but are compatible: broadcasting virtually replicates the smaller tensor along the missing axes without copying memory. The compatibility rule is simple: align shapes from the right; two axes are compatible if they are equal, or one of them is \(1\).

Example 3.28 (Bias addition by broadcasting). Let \(\mathbf{A} \in \mathbb{R}^{4 \times 3}\) be a matrix of pre-activations for \(4\) data points (rows) with \(3\) output units (columns), and \(\mathbf{b} \in \mathbb{R}^{3}\) a bias vector. The expression \(\mathbf{A} + \mathbf{b}\) aligns shapes from the right: \(\mathbf{A}\) is \((4,3)\), \(\mathbf{b}\) is treated as \((1,3)\). The axis-0 mismatch (\(4\) vs \(1\)) is broadcastable; \(\mathbf{b}\) is virtually replicated across the four rows. Complexity: \(4 \cdot 3 = 12\) adds; memory: zero extra bytes for the replication.

Reductions along an axis. Summing all entries along one axis of a rank-\(k\) tensor produces a rank-\((k{-}1)\) tensor. Costs \(\Theta(\prod_i d_i)\) FLOPs where \(d_i\) is the size of the \(i\)-th axis. For \(\mathbf{A} \in \mathbb{R}^{2 \times 3}\) with rows \((1,2,3)\) and \((4,5,6)\): sum(axis=0) collapses rows to \((5,7,9)\) at cost \(3\) adds; sum(axis=1) collapses columns to \((6,15)\) at cost \(4\) adds. The same primitive underlies many normalization layers and softmax denominators.

Batched matrix multiplication. Two rank-3 tensors of shapes \((B, m, k)\) and \((B, k, n)\) multiply elementwise across the leading “batch” axis to produce a \((B, m, n)\) tensor whose \(b\)-th slice is the matrix-matrix product of the corresponding input slices. Complexity: \(Bmn(2k-1) \approx 2Bmkn\) FLOPs, exactly \(B\) times the \(mn(2k-1)\) cost of a single matrix-matrix product derived earlier in this chapter.

The “batch axis” is just a free index in front of an ordinary matrix-matrix product. This is the single most important tensor operation in deep learning: a transformer processes a whole minibatch of inputs in one such call, dispatched onto a GPU.

With this glimpse, the chapter is complete; the exercises that follow stay in the matrix world of the chapter proper.

3.8.3 Why This Matters

The arithmetic does not change. A tensor’s underlying storage is still a flat buffer of floats; element access still resolves through an index-to-offset formula; the cost of computation is still measured in FLOPs. What changes is the language: tensors give us a vocabulary to talk about a batch of matrices, an image with multiple channels, or a stack of attention heads, without having to flatten the data into a single long vector and lose all the structure.

This vocabulary is the working language of every modern AI framework. Every PyTorch, JAX, or TensorFlow call operates on tensors; every model parameter, every activation, every gradient is a tensor. The matrix algebra of this chapter is the grammar of these libraries; tensor operations are how that grammar scales.

We mention tensors here to redeem two earlier promises: the footnote in this chapter on the rank-3 RGB-image structure, and the remark in Chapter 2 that higher-order Taylor expansions involve higher-order derivative tensors. Both promises are made good. Further structure (mode-\(n\) products, CP and Tucker decompositions, and the broader tensor-decomposition literature) is beyond the scope of this course but appears in later machine-learning courses as native operations in the deep-learning frameworks those courses use.

Exercises

Below is a set of exercises related to the content of Chapter 3. The exercises are partitioned by difficulty. Programming questions should be completed in Python using the NumPy library.

EASY EXERCISES

  1. E1.
    Matrix Arithmetic. Given matrices \(\mathbf{A} = \begin{bmatrix} 1 & 0 \\ -2 & 3 \end{bmatrix}\), \(\mathbf{B} = \begin{bmatrix} 5 & 1 \\ 0 & -1 \end{bmatrix}\), and scalar \(\alpha = -2\), compute \(\mathbf{C} = \alpha\mathbf{A} + \mathbf{B}^\top\).
  2. E2.
    Matrix Products. For the matrices \(\mathbf{A}\) and \(\mathbf{B}\) from E1, compute both \(\mathbf{A}\mathbf{B}\) and \(\mathbf{B}\mathbf{A}\). Is matrix multiplication commutative in this case?
  3. E3.
    Outer Product. Compute the outer product \(\mathbf{x}\mathbf{y}^\top\) for the vectors \(\mathbf{x} = \begin{bmatrix} 1 \\ 2 \\ 3 \end{bmatrix}\) and \(\mathbf{y} = \begin{bmatrix} -1 \\ 0 \\ 1 \end{bmatrix}\). What is the resulting matrix?
  4. E4.
    Matrix Norms. For the matrix \(\mathbf{M} = \begin{bmatrix} 1 & -2 \\ 3 & -4 \end{bmatrix}\), compute its Frobenius norm \(\|\mathbf{M}\|_F\), its element-wise \(\ell_1\)-norm \(\|\mathbf{M}\|_1\), and its max norm \(\|\mathbf{M}\|_\infty\).
  5. E5.
    Complexity Analysis. An algorithm’s main step involves computing \(\mathbf{y} = (\mathbf{A}\mathbf{B})\mathbf{x}\), where \(\mathbf{A} \in \mathbb{R}^{100 \times 200}\), \(\mathbf{B} \in \mathbb{R}^{200 \times 50}\), and \(\mathbf{x} \in \mathbb{R}^{50}\).
    1. a)
      What is the approximate complexity (in FLOPs) of computing \(\mathbf{C} = \mathbf{A}\mathbf{B}\) first, then \(\mathbf{y} = \mathbf{C}\mathbf{x}\)?
    2. b)
      What is the approximate complexity of computing \(\mathbf{v} = \mathbf{B}\mathbf{x}\) first, then \(\mathbf{y} = \mathbf{A}\mathbf{v}\)?
    3. c)
      Which order of operations is more efficient?
  6. E6.
    Identifying Matrix Properties. For each of the following matrices, state whether it is symmetric, diagonal, sparse, or none of these. \[ \mathbf{M}_1 = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}, \quad \mathbf{M}_2 = \begin{bmatrix} 5 & 0 \\ 0 & -1 \end{bmatrix}, \quad \mathbf{M}_3 = \begin{bmatrix} 1 & 7 & 0 \\ 7 & 2 & 3 \\ 0 & 3 & 9 \end{bmatrix}. \]
  7. E7.
    Matrix-Vector Multiplication. Given \(\mathbf{A} = \begin{bmatrix} 1 & 0 & -1 \\ 2 & 3 & 0 \end{bmatrix}\) and \(\mathbf{x} = \begin{bmatrix} 5 \\ 1 \\ 2 \end{bmatrix}\), compute the product \(\mathbf{A}\mathbf{x}\) using both the row-wise (inner product) view and the column-wise (linear combination) view.
  8. E8.
    Gradient of a Matrix Function. Using the rules from the chapter, find the gradient of the function \(f(\mathbf{W}) = \langle \mathbf{A}, \mathbf{W} \rangle\), where \(\mathbf{A}\) is a constant matrix of the same size as \(\mathbf{W}\).
  9. E9.
    Python: Matrix Creation. Write a Python script using NumPy to create the following matrices: a \(4 \times 4\) identity matrix, a \(3 \times 5\) matrix of all zeros, and a \(2 \times 2\) matrix with the values \(\begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}\).
  10. E10.
    Dimensions Check. Let \(\mathbf{A} \in \mathbb{R}^{5 \times 3}\), \(\mathbf{B} \in \mathbb{R}^{3 \times 7}\), and \(\mathbf{C} \in \mathbb{R}^{5 \times 7}\). Which of the following operations are valid? a) \(\mathbf{A}\mathbf{B}\)   b) \(\mathbf{B}\mathbf{A}\)   c) \(\mathbf{A}+\mathbf{C}\)   d) \((\mathbf{A}\mathbf{B})^\top - \mathbf{C}\)

MEDIUM EXERCISES

  1. M1.
    Properties of Transpose. Prove that for any two matrices \(\mathbf{A} \in \mathbb{R}^{m \times n}\) and \(\mathbf{B} \in \mathbb{R}^{n \times p}\), the property \((\mathbf{A}\mathbf{B})^\top = \mathbf{B}^\top\mathbf{A}^\top\) holds. Use the summation definition of matrix multiplication.
  2. M2.
    Matrix Inner Product and Orthogonality. Given \(\mathbf{A} = \begin{bmatrix} 1 & 1 \\ 1 & 1 \end{bmatrix}\) and \(\mathbf{B} = \begin{bmatrix} 1 & -1 \\ -1 & 1 \end{bmatrix}\), compute their inner product \(\langle \mathbf{A}, \mathbf{B} \rangle\). What does the result imply about the “angle” between these two matrices in the space of \(2 \times 2\) matrices?
  3. M3.
    Symmetric and Skew-Symmetric Decomposition. A square matrix \(\mathbf{S}\) is symmetric if \(\mathbf{S}^\top = \mathbf{S}\). A matrix \(\mathbf{K}\) is skew-symmetric if \(\mathbf{K}^\top = -\mathbf{K}\).
    1. a)
      Show that any square matrix \(\mathbf{A}\) can be written as the sum of a symmetric and a skew-symmetric matrix. (Hint: Consider \(\frac{1}{2}(\mathbf{A}+\mathbf{A}^\top)\) and \(\frac{1}{2}(\mathbf{A}-\mathbf{A}^\top)\)).
    2. b)
      Show that for any symmetric matrix \(\mathbf{S}\) and skew-symmetric matrix \(\mathbf{K}\) of the same size, their inner product \(\langle \mathbf{S}, \mathbf{K} \rangle = 0\).
  4. M4.
    Expanding the Frobenius Norm. A common loss function in machine learning is the squared Frobenius norm of a residual, \(f(\mathbf{X}) = \|\mathbf{Y} - \mathbf{X}\|_F^2\). Show that this function can be expanded as \(f(\mathbf{X}) = \|\mathbf{Y}\|_F^2 - 2\langle \mathbf{Y}, \mathbf{X} \rangle + \|\mathbf{X}\|_F^2\).
  5. M5.
    Block Matrix Multiplication. Given the block matrices \(\mathbf{A} = \begin{bmatrix} \mathbf{A}_{11} & \mathbf{A}_{12} \\ \mathbf{A}_{21} & \mathbf{A}_{22} \end{bmatrix}\) and \(\mathbf{B} = \begin{bmatrix} \mathbf{B}_{11} \\ \mathbf{B}_{21} \end{bmatrix}\), where each block is a \(2 \times 2\) matrix, compute the product \(\mathbf{A}\mathbf{B}\). First express the result in terms of blocks, then substitute the actual matrices below and compute the final \(4 \times 2\) matrix. \[ \begin{aligned} \mathbf{A}_{11} &= \mathbf{I}, \quad \mathbf{A}_{12} = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}, \quad \mathbf{A}_{21} = \mathbf{0}, \quad \mathbf{A}_{22} = \begin{bmatrix} 5 & 0 \\ 0 & 5 \end{bmatrix}, \\ \mathbf{B}_{11} &= \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}, \quad \mathbf{B}_{21} = \begin{bmatrix} 1 & 1 \\ 0 & 0 \end{bmatrix}. \end{aligned} \]
  6. M6.
    Gradient of a Quadratic Form. Find the gradient of the function \(f(\mathbf{W}) = \frac{1}{2} \|\mathbf{XW}\|_F^2\) with respect to the matrix \(\mathbf{W}\), where \(\mathbf{X}\) is a constant matrix. (Hint: Write it as a summation, \(f(\mathbf{W}) = \frac{1}{2}\sum_{i}\sum_{j} \left(\sum_{k} X_{ik} W_{kj}\right)^2\), and compute each partial derivative \(\partial f / \partial W_{kl}\).)
  7. M7.
    First-Order Taylor Approximation. Find the first-order Taylor approximation for the function \(f(\mathbf{W}) = \text{Tr}(\mathbf{W}^\top\mathbf{W})\) around the point \(\mathbf{W}_0 = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}\).
  8. M8.
    Python: Image Similarity. An image can be represented as a matrix of pixel values. Create two simple \(10 \times 10\) NumPy arrays, img1 and img2. For example, img1 could be all zeros with a \(3 \times 3\) block of ones in the center, and img2 could be a similar pattern but slightly shifted.
    1. a)
      Compute the distance between them using the Frobenius norm: \(\|\text{img1} - \text{img2}\|_F\).
    2. b)
      Normalize both images by dividing each by its own Frobenius norm. This creates unit-norm matrices norm_img1 and norm_img2.
    3. c)
      Compute the inner product \(\langle \text{norm\_img1}, \text{norm\_img2} \rangle\). This value is the cosine similarity. A value close to 1 means they are very similar.
  9. M9.
    Trace and Inner Product. Show that the matrix inner product can be written in terms of the sum of inner products of the matrix’s columns. That is, prove that \(\langle \mathbf{A}, \mathbf{B} \rangle = \sum_{j=1}^p \langle \mathbf{a}_{:,j}, \mathbf{b}_{:,j} \rangle\).
  10. M10.
    Gradient Descent for Matrix Completion. Imagine you have a matrix \(\mathbf{Y}\) with some missing entries. A simple approach to “matrix completion” is to find a matrix \(\mathbf{W}\) that is “close” to \(\mathbf{Y}\) on the entries we do observe. Let \(\Omega\) be the set of \((i,j)\) indices where \(Y_{ij}\) is known. Our objective is \(f(\mathbf{W}) = \sum_{(i,j) \in \Omega} (Y_{ij} - W_{ij})^2\). Derive the gradient descent update rule for \(\mathbf{W}\). (Hint: The gradient will be a sparse matrix).

HARD EXERCISES

  1. H1.
    The Trace as an Inner Product. Prove that for any two matrices \(\mathbf{A}, \mathbf{B} \in \mathbb{R}^{m \times p}\), \(\text{Tr}(\mathbf{A}^\top \mathbf{B}) = \sum_{i=1}^m \sum_{j=1}^p A_{ij} B_{ij}\). Use the definitions of trace and matrix multiplication.
  2. H2.
    Properties of the Trace (Cyclic Property). Prove the cyclic property of the trace: for any matrices \(\mathbf{A} \in \mathbb{R}^{m \times n}\), \(\mathbf{B} \in \mathbb{R}^{n \times p}\), and \(\mathbf{C} \in \mathbb{R}^{p \times m}\) that result in a square matrix product, it holds that \(\text{Tr}(\mathbf{A}\mathbf{B}\mathbf{C}) = \text{Tr}(\mathbf{B}\mathbf{C}\mathbf{A}) = \text{Tr}(\mathbf{C}\mathbf{A}\mathbf{B})\).
  3. H3.
    Gradient of Multivariate Regression. Derive the gradient for the multivariate linear regression problem, \(f(\mathbf{W}) = \frac{1}{2} \|\mathbf{Y} - \mathbf{XW}\|_F^2\), with respect to the weight matrix \(\mathbf{W}\). Show that the gradient is \(\nabla f(\mathbf{W}) = \mathbf{X}^\top(\mathbf{XW} - \mathbf{Y})\). (Hint: Use the chain rule and properties of the trace).
  4. H4.
    Python: Matrix Multiplication Complexity. Write a Python script to empirically verify the \(O(n^3)\) complexity of matrix multiplication for square matrices.
    1. a)
      Create a loop for matrix sizes \(n = 100, 200, 300, \dots, 1000\).
    2. b)
      Inside the loop, generate two random \(n \times n\) matrices using np.random.rand(n, n).
    3. c)
      Use the time module (e.g., time.time()) to measure the execution time of multiplying them using np.dot().
    4. d)
      Plot the execution time versus \(n\) on a standard plot, and also on a log-log plot. If the complexity is \(O(n^3)\), the log-log plot should be roughly a straight line. What is the approximate slope of this line?
  5. H5.
    Proof of Associativity. Prove the associative property of matrix multiplication, \((\mathbf{A}\mathbf{B})\mathbf{C} = \mathbf{A}(\mathbf{B}\mathbf{C})\), using only the summation definition \((\mathbf{A}\mathbf{B})_{ij} = \sum_k A_{ik}B_{kj}\).