Artificial Intelligence • Mathematical Foundations • 16 min read

Vector and Matrix Operations

Vectors and matrices do more than organize numbers. Their operations allow a computer to combine features, measure similarity, transform representations, and calculate predictions. These computations appear throughout machine learning, from a simple linear model to a large neural network.

This article builds on Vectors and Matrices, which introduces coordinates, rows, columns, and shapes. Here, the focus is on what calculations can be performed, why their dimensions matter, and how those calculations appear in AI software.

Begin with a small prediction

Imagine a simple model uses two inputs: hours studied and practice questions completed. We represent a student by a vector:

x=[35]\mathbf{x}=\begin{bmatrix}3\\5\end{bmatrix}

The model assigns each input a weight:

w=[21]\mathbf{w}=\begin{bmatrix}2\\1\end{bmatrix}

To combine the two inputs into one score, multiply corresponding entries and add:

wTx=(2×3)+(1×5)=11\mathbf{w}^{T}\mathbf{x}=(2\times3)+(1\times5)=11

This operation is called a dot product. The score of 11 is only an illustrative model output, not a calibrated grade or probability. Yet this small calculation captures an important pattern: many machine-learning models build predictions from weighted combinations of numerical features.

Now imagine 100 students. Instead of calculating one student at a time, arrange their feature vectors into a matrix and use matrix–vector multiplication to compute a whole collection of scores. The mathematics stays consistent, and numerical libraries can perform the work efficiently.

Different operations answer different questions:

  • Addition combines values in matching positions.
  • Dot product produces one number from corresponding vector entries.
  • Norm describes magnitude, such as vector length.
  • Cosine similarity compares directions rather than raw magnitudes.
  • Matrix multiplication composes weighted combinations and transformations.

Watch the shapes: A vector of three features cannot be dotted with a vector of two weights without changing the inputs. Checking dimensions is the first step before choosing an operation.

The role of shape in mathematical operations

Before calculating with a vector or matrix, inspect its shape. Shape describes how many entries an object has along each axis and determines whether a particular operation is defined.

OperationShape requirementOutput shape
Vector additionTwo vectors of the same lengthSame length
Dot productTwo vectors of the same lengthScalar
Matrix additionMatrices with identical shapesSame matrix shape
Matrix–vector multiplicationAn m×nm\times n matrix and a length-nn column vectorLength-mm column vector
Matrix multiplicationAn m×nm\times n matrix and an n×pn\times p matrixm×pm\times p matrix
TransposeAny matrixRows and columns exchanged

For example, a 2×32\times3 matrix can multiply a 3×43\times4 matrix because the two inner dimensions match. The result has shape 2×42\times4.

(2×3) (3×4)⟶2×4(2\times\boxed{3})\,(\boxed{3}\times4)\longrightarrow 2\times4

By contrast, ordinary matrix multiplication between a 2×32\times3 matrix and a 2×42\times4 matrix is undefined because the inner dimensions do not match.

Important: Rules for mathematical operations and rules for array-library broadcasting are not identical. NumPy can automatically expand some compatible array shapes for element-wise operations. This convenience does not change the mathematical definition of matrix multiplication.

Vector addition and subtraction

Vector addition combines corresponding coordinates of two vectors. The vectors must belong to the same coordinate space, or at least have compatible coordinate representations for the intended application.

For vectors in R3\mathbb{R}^3:

a=[231],b=[4−12]\mathbf{a}=\begin{bmatrix}2\\3\\1\end{bmatrix},\qquad \mathbf{b}=\begin{bmatrix}4\\-1\\2\end{bmatrix}

Their sum is:

a+b=[2+43+(−1)1+2]=[623]\mathbf{a}+\mathbf{b} =\begin{bmatrix}2+4\\3+(-1)\\1+2\end{bmatrix} =\begin{bmatrix}6\\2\\3\end{bmatrix}

Vector subtraction works coordinate by coordinate as well:

a−b=[2−43−(−1)1−2]=[−24−1]\mathbf{a}-\mathbf{b} =\begin{bmatrix}2-4\\3-(-1)\\1-2\end{bmatrix} =\begin{bmatrix}-2\\4\\-1\end{bmatrix}

For example, two vectors might represent measurements of the same features at different times. Their difference describes how those features changed. However, adding unrelated features is not automatically meaningful: the coordinates must refer to corresponding quantities.

Scalar multiplication

Multiplying a vector by a scalar multiplies each coordinate by the same number. For c∈Rc\in\mathbb{R}:

ca=[ca1ca2⋮can]c\mathbf{a} =\begin{bmatrix}ca_1\\ca_2\\\vdots\\ca_n\end{bmatrix}

With c=2c=2 and a=[2,3,1]T\mathbf{a}=[2,3,1]^{\mathsf T}:

2a=[462]2\mathbf{a}=\begin{bmatrix}4\\6\\2\end{bmatrix}

In a geometric interpretation, a positive scalar changes a vector’s length without changing its direction. A negative scalar reverses its direction as well as scaling its length. In an AI system, scalar multiplication can rescale features, weights, or numerical updates.

The dot product

The dot product, also called the inner product in ordinary Euclidean coordinate space, multiplies corresponding coordinates and adds the results. For two vectors of length nn:

a⋅b=aTb=∑i=1naibi\mathbf{a}\cdot\mathbf{b} =\mathbf{a}^{\mathsf T}\mathbf{b} =\sum_{i=1}^{n}a_i b_i

It produces one number, not another vector.

Using the vectors above:

a⋅b=(2)(4)+(3)(−1)+(1)(2)=8−3+2=7\begin{aligned} \mathbf{a}\cdot\mathbf{b} &=(2)(4)+(3)(-1)+(1)(2)\\ &=8-3+2\\ &=7 \end{aligned}

The dot product is different from element-wise multiplication. Element-wise multiplication produces the coordinate values [8,−3,2][8,-3,2]; the dot product adds those values to produce 77.

Geometric meaning

For nonzero Euclidean vectors, the dot product also relates their lengths and the angle θ\theta between them:

a⋅b=∥a∥2 ∥b∥2cos⁡θ\mathbf{a}\cdot\mathbf{b} =\lVert\mathbf{a}\rVert_2\,\lVert\mathbf{b}\rVert_2\cos\theta

This gives a useful geometric interpretation:

  • A positive dot product indicates an angle smaller than 90∘90^\circ.
  • A zero dot product indicates perpendicular, or orthogonal, vectors, provided both vectors are nonzero.
  • A negative dot product indicates an angle larger than 90∘90^\circ.

The numerical dot product depends on both lengths and angle. A larger result does not, by itself, establish greater directional similarity if the vector lengths differ.

Dot products in a prediction model

A simple linear prediction model combines input features x\mathbf{x} with learned weights w\mathbf{w} and a bias bb:

y^=wTx+b\hat y=\mathbf{w}^{\mathsf T}\mathbf{x}+b

Suppose the inputs are two study-related features and the parameters are:

x=[23],w=[45],b=1\mathbf{x}=\begin{bmatrix}2\\3\end{bmatrix},\quad \mathbf{w}=\begin{bmatrix}4\\5\end{bmatrix},\quad b=1

Then:

y^=(4)(2)+(5)(3)+1=24\hat y=(4)(2)+(5)(3)+1=24

The result is a raw numerical prediction in whatever units the model is designed to produce. This calculation alone does not say whether the prediction is accurate or whether the parameters were properly learned. It shows how a model can combine several inputs into one output using a dot product.

Vector magnitude and norms

A norm measures the size of a vector according to specified mathematical rules. The most familiar norm is the Euclidean norm, or L2L_2 norm:

∥x∥2=∑i=1nxi2\lVert\mathbf{x}\rVert_2=\sqrt{\sum_{i=1}^{n}x_i^2}

For v=[3,4]T\mathbf{v}=[3,4]^{\mathsf T}:

∥v∥2=32+42=25=5\lVert\mathbf{v}\rVert_2=\sqrt{3^2+4^2}=\sqrt{25}=5

In two-dimensional geometry, this is the length of the arrow from the origin to (3,4)(3,4). The same calculation extends to numerical vectors with many coordinates.

Other norms worth recognizing include:

NormFormulaWhat it measures
L1L_1∥x∥1=∑i∣xi∣\lVert\mathbf{x}\rVert_1=\sum_i\lvert x_i\rvertSum of absolute coordinate values
L2L_2∥x∥2=∑ixi2\lVert\mathbf{x}\rVert_2=\sqrt{\sum_i x_i^2}Euclidean magnitude
L∞L_\infty∥x∥∞=max⁡i∣xi∣\lVert\mathbf{x}\rVert_\infty=\max_i\lvert x_i\rvertLargest absolute coordinate value

Norms are useful in optimization, regularization, measuring numerical differences, and comparing embeddings.

Normalizing a vector

Unit normalization divides a nonzero vector by its norm so that the result has length 11:

v^=v∥v∥2\hat{\mathbf{v}}=\frac{\mathbf{v}}{\lVert\mathbf{v}\rVert_2}

For v=[3,4]T\mathbf{v}=[3,4]^{\mathsf T}:

v^=[3/54/5]=[0.60.8]\hat{\mathbf{v}}=\begin{bmatrix}3/5\\4/5\end{bmatrix} =\begin{bmatrix}0.6\\0.8\end{bmatrix}

Its Euclidean norm is 11. The operation preserves the vector’s direction but removes its original magnitude.

Edge case: The zero vector has norm 00, so dividing it by its norm is undefined. Software must handle zero or near-zero norms explicitly rather than divide blindly.

Cosine similarity

Cosine similarity compares the orientation of two nonzero vectors. It is their dot product divided by the product of their Euclidean norms:

cos_sim⁡(a,b)=a⋅b∥a∥2∥b∥2\operatorname{cos\_sim}(\mathbf{a},\mathbf{b}) =\frac{\mathbf{a}\cdot\mathbf{b}} {\lVert\mathbf{a}\rVert_2\lVert\mathbf{b}\rVert_2}

For real-valued vectors, the value lies between −1-1 and 11:

  • 11 means the vectors point in the same direction.
  • 00 means they are perpendicular.
  • −1-1 means they point in opposite directions.

For example, with u=[1,0]T\mathbf{u}=[1,0]^{\mathsf T} and v=[1,1]T\mathbf{v}=[1,1]^{\mathsf T}:

cos_sim⁡(u,v)=11⋅2≈0.7071\operatorname{cos\_sim}(\mathbf{u},\mathbf{v}) =\frac{1}{1\cdot\sqrt{2}} \approx0.7071

Cosine similarity is widely used to compare embeddings, the numerical vectors produced by language and other AI models. It provides a geometric similarity score; it is not automatically a probability, a guarantee of semantic equivalence, or a measure of factual correctness. Whether the score is useful depends on how the embedding model was trained and evaluated.

Matrix addition, subtraction, and scalar multiplication

Two matrices can be added or subtracted entry by entry when they have the same shape.

Let:

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

Then:

A+B=[681012]A+B=\begin{bmatrix}6&8\\10&12\end{bmatrix}

A scalar also multiplies every matrix entry:

3A=[36912]3A=\begin{bmatrix}3&6\\9&12\end{bmatrix}

A 2×22\times2 matrix cannot be added directly to a 3×23\times2 matrix under ordinary matrix addition. The two objects do not have matching entries at every row-and-column position.

These operations are used when adjusting numerical data, combining compatible representations, or applying parameter updates during learning.

The transpose of a matrix

The transpose of a matrix exchanges its rows and columns. It is written ATA^{\mathsf T}.

For example:

A=[123456]⟹AT=[142536]A=\begin{bmatrix} 1&2&3\\ 4&5&6 \end{bmatrix} \quad\Longrightarrow\quad A^{\mathsf T}=\begin{bmatrix} 1&4\\ 2&5\\ 3&6 \end{bmatrix}

The original matrix has shape 2×32\times3; its transpose has shape 3×23\times2.

Transposition is useful when a calculation needs to work with features as columns rather than rows, or when a row vector must be represented as a column vector. Two useful identities are:

(AT)T=A(A^{\mathsf T})^{\mathsf T}=A

and, whenever the multiplication is defined,

(AB)T=BTAT(AB)^{\mathsf T}=B^{\mathsf T}A^{\mathsf T}

Notice that the order reverses in the second identity.

Matrix–vector multiplication

A matrix can transform a vector into another vector. If AA has shape m×nm\times n and x\mathbf{x} has nn coordinates, then AxA\mathbf{x} has mm coordinates.

Each output coordinate is the dot product of one matrix row with the input vector.

Let:

A=[1200−13],x=[214]A=\begin{bmatrix} 1&2&0\\ 0&-1&3 \end{bmatrix},\qquad \mathbf{x}=\begin{bmatrix}2\\1\\4\end{bmatrix}

Matrix AA has shape 2×32\times3, and x\mathbf{x} has three coordinates. Multiplication is defined:

Ax=[(1)(2)+(2)(1)+(0)(4)(0)(2)+(−1)(1)+(3)(4)]=[411]\begin{aligned} A\mathbf{x} &=\begin{bmatrix} (1)(2)+(2)(1)+(0)(4)\\ (0)(2)+(-1)(1)+(3)(4) \end{bmatrix}\\[6pt] &=\begin{bmatrix}4\\11\end{bmatrix} \end{aligned}

The input has three coordinates; the output has two. The matrix defines how information from the three input coordinates is combined into two output coordinates.

This is central to a neural network’s linear layer. A layer may compute:

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

Here, WW is a weight matrix, x\mathbf{x} is the input vector, and b\mathbf{b} is a bias vector. A nonlinear activation function is often applied afterward. The weights and biases are typically adjusted during training.

Matrix multiplication

Matrix multiplication combines rows from the left matrix with columns from the right matrix using dot products. It is not the same as multiplying two matrices entry by entry.

If A∈Rm×nA\in\mathbb{R}^{m\times n} and B∈Rn×pB\in\mathbb{R}^{n\times p}, then:

C=AB∈Rm×pC=AB\in\mathbb{R}^{m\times p}

The entry in row ii, column jj of CC is:

cij=∑k=1naikbkjc_{ij}=\sum_{k=1}^{n}a_{ik}b_{kj}

Worked example

Let:

A=[1200−13],B=[21041−2]A=\begin{bmatrix} 1&2&0\\ 0&-1&3 \end{bmatrix},\qquad B=\begin{bmatrix} 2&1\\ 0&4\\ 1&-2 \end{bmatrix}

The shapes are 2×32\times3 and 3×23\times2, so the result will be 2×22\times2.

For the first row and second column of the product, multiply the first row of AA by the second column of BB:

c12=(1)(1)+(2)(4)+(0)(−2)=9c_{12}=(1)(1)+(2)(4)+(0)(-2)=9

Performing the same calculation for all four entries gives:

AB=[293−10]AB=\begin{bmatrix} 2&9\\ 3&-10 \end{bmatrix}
Matrix multiplication of a two-by-three matrix and a three-by-two matrix produces a two-by-two matrix. The first row of A and second column of B combine to produce the value nine.
One entry of a matrix product comes from the dot product of a row in the left matrix and a column in the right matrix.

Why multiplication order matters

Matrix multiplication is generally not commutative:

AB≠BAin generalAB\ne BA\qquad\text{in general}

Sometimes BABA is not defined at all. Even when both products exist, their shapes or values may differ. In the previous example, ABAB has shape 2×22\times2, whereas BABA has shape 3×33\times3.

Matrix multiplication is associative when dimensions are compatible:

(AB)C=A(BC)(AB)C=A(BC)

It is also distributive over addition when the shapes permit it:

A(B+C)=AB+ACA(B+C)=AB+AC

These properties matter when software combines multiple transformations or rearranges computations for efficiency.

Identity matrices

The identity matrix InI_n is a square matrix with ones on the main diagonal and zeros elsewhere. It acts like the number 11 under compatible matrix multiplication:

Inx=x,AIn=AI_n\mathbf{x}=\mathbf{x},\qquad AI_n=A

For instance:

[1001][34]=[34]\begin{bmatrix}1&0\\0&1\end{bmatrix} \begin{bmatrix}3\\4\end{bmatrix} =\begin{bmatrix}3\\4\end{bmatrix}

An inverse matrix, when one exists, reverses the transformation of a square matrix. Not every square matrix has an inverse, and ordinary division by a matrix is not a defined general operation. In numerical computing, solving a linear system directly is usually preferable to calculating an inverse explicitly.

Element-wise multiplication versus matrix multiplication

One of the most common programming mistakes in introductory AI work is confusing two different operations.

For two matrices of the same shape, element-wise multiplication, also called the Hadamard product, multiplies corresponding entries:

[1234]⊙[5678]=[5122132]\begin{bmatrix}1&2\\3&4\end{bmatrix} \odot \begin{bmatrix}5&6\\7&8\end{bmatrix} = \begin{bmatrix}5&12\\21&32\end{bmatrix}

Ordinary matrix multiplication instead computes row-by-column dot products:

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

These two results are different because the operations answer different questions.

Mathematical operationNumPy expressionBehavior
Element-wise multiplicationA * BMultiplies corresponding elements, with broadcasting where applicable
Matrix multiplicationA @ BComputes row-by-column dot products
Vector dot producta @ b or np.dot(a, b)Produces a scalar for two one-dimensional vectors
Transpose of a 2D matrixA.TExchanges the two axes
Euclidean normnp.linalg.norm(a)Produces a magnitude

Working with vector and matrix operations in NumPy

NumPy provides efficient array operations and a convenient way to express the calculations developed above. Its default conventions require attention: a one-dimensional array has shape (n,), not (n, 1) or (1, n).

Vector operations in Python

import numpy as np

a = np.array([2, 3, 1], dtype=float)
b = np.array([4, -1, 2], dtype=float)

print("sum:", a + b)                # [6. 2. 3.]
print("difference:", a - b)         # [-2.  4. -1.]
print("scaled:", 2 * a)             # [4. 6. 2.]
print("element-wise:", a * b)       # [ 8. -3.  2.]
print("dot product:", a @ b)        # 7.0

v = np.array([3.0, 4.0])
length = np.linalg.norm(v)
unit_v = v / length

print("length:", length)            # 5.0
print("unit vector:", unit_v)       # [0.6 0.8]

assert np.isclose(np.linalg.norm(unit_v), 1.0)

Matrix operations in Python

import numpy as np

A = np.array([
    [1, 2, 0],
    [0, -1, 3],
])

B = np.array([
    [2, 1],
    [0, 4],
    [1, -2],
])

x = np.array([2, 1, 4])

print("A shape:", A.shape)       # (2, 3)
print("B shape:", B.shape)       # (3, 2)
print("A transpose:", A.T.shape) # (3, 2)
print("A @ x:", A @ x)           # [ 4 11]
print("A @ B:\n", A @ B)
# [[  2   9]
#  [  3 -10]]

assert (A @ x).tolist() == [4, 11]
assert (A @ B).tolist() == [[2, 9], [3, -10]]

In NumPy, A @ x returns a one-dimensional array of shape (2,) because x has shape (3,). To obtain an explicit two-dimensional column array of shape (2, 1), reshape the input before multiplication:

x_column = x.reshape(3, 1)
result_column = A @ x_column

print(result_column.shape)  # (2, 1)

Likewise, transposing a one-dimensional array with .T does not turn it into a row or column matrix. Use reshape or an additional axis when the distinction is important.

A batch of predictions with matrix multiplication

Machine-learning datasets often store one example per row and one feature per column. With an input matrix X∈Rm×nX\in\mathbb{R}^{m\times n}, a weight vector w∈Rn\mathbf{w}\in\mathbb{R}^{n}, and a scalar bias bb, all mm predictions can be calculated together:

y^=Xw+b1\hat{\mathbf{y}}=X\mathbf{w}+b\mathbf{1}

Here, 1\mathbf{1} is a length-mm vector of ones. Adding bb in NumPy broadcasts the same scalar bias to every prediction.

import numpy as np

# Three students, two input features per student.
X = np.array([
    [2.0, 1.0],
    [4.0, 3.0],
    [5.0, 4.0],
])

w = np.array([1.5, 2.0])
b = 0.5

predictions = X @ w + b

print("shape:", predictions.shape)  # (3,)
print("predictions:", predictions)   # [ 5.5 12.5 16. ]

assert np.allclose(predictions, [5.5, 12.5, 16.0])

This is a forward calculation, not training. Training would additionally require appropriate target values, a loss function, and a method for updating the parameters w\mathbf{w} and bb.

Common mistakes and how to avoid them

MistakeWhy it mattersBetter approach
Adding vectors with mismatched meaningsCorresponding coordinates represent different features or unitsEstablish and preserve a consistent feature order
Multiplying incompatible matricesInner dimensions do not matchCheck shapes before using @
Using * when matrix multiplication is intendedComputes element-wise products insteadUse @ for matrix multiplication
Treating every dot product as a similarity scoreMagnitude affects the resultNormalize or use cosine similarity when appropriate
Normalizing a zero vectorDivision by zero is undefinedHandle zero norms explicitly
Assuming x.T changes a 1D NumPy vector’s shapeA 1D array has only one axisUse reshape(n, 1) or reshape(1, n)
Assuming multiplication order never mattersMatrix multiplication is generally noncommutativeWrite transformations in the intended order
Treating a computed score as a trained modelA formula alone does not learn parametersSeparate forward inference from optimization

For large AI workloads, there are further engineering concerns such as floating-point precision, memory use, and computational efficiency. Those become especially important when operating on high-dimensional tensors or using GPU-accelerated libraries.

Check your understanding

  1. If a=[2,3]T\mathbf{a}=[2,3]^{\mathsf T} and b=[4,5]T\mathbf{b}=[4,5]^{\mathsf T}, what are a+b\mathbf{a}+\mathbf{b} and a⋅b\mathbf{a}\cdot\mathbf{b}?
  2. Calculate the Euclidean norm of v=[6,8]T\mathbf{v}=[6,8]^{\mathsf T}. What is its unit vector?
  3. Can a 4×34\times3 matrix multiply a 3×23\times2 matrix? What is the result’s shape?
  4. For A=[1234]A=\begin{bmatrix}1&2\\3&4\end{bmatrix} and B=[5678]B=\begin{bmatrix}5&6\\7&8\end{bmatrix}, why are A * B and A @ B different?
  5. What does np.array([1, 2, 3]).T.shape return?
Show the worked answers
  1. The sum is [6,8]T[6,8]^{\mathsf T}. The dot product is (2)(4)+(3)(5)=23(2)(4)+(3)(5)=23.
  2. The norm is 62+82=10\sqrt{6^2+8^2}=10. The unit vector is [0.6,0.8]T[0.6,0.8]^{\mathsf T}.
  3. Yes. The inner dimensions are both 33, so the output shape is 4×24\times2.
  4. A * B multiplies corresponding entries and gives [5122132]\begin{bmatrix}5&12\\21&32\end{bmatrix}. A @ B computes row-by-column dot products and gives [19224350]\begin{bmatrix}19&22\\43&50\end{bmatrix}.
  5. It returns (3,). Transposition does not change the shape of a one-dimensional NumPy array.

References

  1. MIT OpenCourseWare — 18.06SC Linear Algebra. Lectures, exercises, and explanations covering matrix operations, linear transformations, and vector spaces.
  2. NumPy documentation — numpy.matmul. Matrix multiplication semantics and shape behavior.
  3. NumPy documentation — numpy.linalg.norm. Vector and matrix norm definitions used in numerical computing.
  4. NumPy documentation — Broadcasting. How arrays of compatible shapes interact in element-wise operations.

Related articles in

Image preview

Fit