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:
The model assigns each input a weight:
To combine the two inputs into one score, multiply corresponding entries and add:
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.
| Operation | Shape requirement | Output shape |
|---|---|---|
| Vector addition | Two vectors of the same length | Same length |
| Dot product | Two vectors of the same length | Scalar |
| Matrix addition | Matrices with identical shapes | Same matrix shape |
| Matrix–vector multiplication | An matrix and a length- column vector | Length- column vector |
| Matrix multiplication | An matrix and an matrix | matrix |
| Transpose | Any matrix | Rows and columns exchanged |
For example, a matrix can multiply a matrix because the two inner dimensions match. The result has shape .
By contrast, ordinary matrix multiplication between a matrix and a 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 :
Their sum is:
Vector subtraction works coordinate by coordinate as well:
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 :
With and :
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 :
It produces one number, not another vector.
Using the vectors above:
The dot product is different from element-wise multiplication. Element-wise multiplication produces the coordinate values ; the dot product adds those values to produce .
Geometric meaning
For nonzero Euclidean vectors, the dot product also relates their lengths and the angle between them:
This gives a useful geometric interpretation:
- A positive dot product indicates an angle smaller than .
- A zero dot product indicates perpendicular, or orthogonal, vectors, provided both vectors are nonzero.
- A negative dot product indicates an angle larger than .
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 with learned weights and a bias :
Suppose the inputs are two study-related features and the parameters are:
Then:
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 norm:
For :
In two-dimensional geometry, this is the length of the arrow from the origin to . The same calculation extends to numerical vectors with many coordinates.
Other norms worth recognizing include:
| Norm | Formula | What it measures |
|---|---|---|
| Sum of absolute coordinate values | ||
| Euclidean magnitude | ||
| Largest 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 :
For :
Its Euclidean norm is . The operation preserves the vector’s direction but removes its original magnitude.
Edge case: The zero vector has norm , 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:
For real-valued vectors, the value lies between and :
- means the vectors point in the same direction.
- means they are perpendicular.
- means they point in opposite directions.
For example, with and :
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:
Then:
A scalar also multiplies every matrix entry:
A matrix cannot be added directly to a 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 .
For example:
The original matrix has shape ; its transpose has shape .
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:
and, whenever the multiplication is defined,
Notice that the order reverses in the second identity.
Matrix–vector multiplication
A matrix can transform a vector into another vector. If has shape and has coordinates, then has coordinates.
Each output coordinate is the dot product of one matrix row with the input vector.
Let:
Matrix has shape , and has three coordinates. Multiplication is defined:
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:
Here, is a weight matrix, is the input vector, and 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 and , then:
The entry in row , column of is:
Worked example
Let:
The shapes are and , so the result will be .
For the first row and second column of the product, multiply the first row of by the second column of :
Performing the same calculation for all four entries gives:
Why multiplication order matters
Matrix multiplication is generally not commutative:
Sometimes is not defined at all. Even when both products exist, their shapes or values may differ. In the previous example, has shape , whereas has shape .
Matrix multiplication is associative when dimensions are compatible:
It is also distributive over addition when the shapes permit it:
These properties matter when software combines multiple transformations or rearranges computations for efficiency.
Identity matrices
The identity matrix is a square matrix with ones on the main diagonal and zeros elsewhere. It acts like the number under compatible matrix multiplication:
For instance:
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:
Ordinary matrix multiplication instead computes row-by-column dot products:
These two results are different because the operations answer different questions.
| Mathematical operation | NumPy expression | Behavior |
|---|---|---|
| Element-wise multiplication | A * B | Multiplies corresponding elements, with broadcasting where applicable |
| Matrix multiplication | A @ B | Computes row-by-column dot products |
| Vector dot product | a @ b or np.dot(a, b) | Produces a scalar for two one-dimensional vectors |
| Transpose of a 2D matrix | A.T | Exchanges the two axes |
| Euclidean norm | np.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 , a weight vector , and a scalar bias , all predictions can be calculated together:
Here, is a length- vector of ones. Adding 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 and .
Common mistakes and how to avoid them
| Mistake | Why it matters | Better approach |
|---|---|---|
| Adding vectors with mismatched meanings | Corresponding coordinates represent different features or units | Establish and preserve a consistent feature order |
| Multiplying incompatible matrices | Inner dimensions do not match | Check shapes before using @ |
Using * when matrix multiplication is intended | Computes element-wise products instead | Use @ for matrix multiplication |
| Treating every dot product as a similarity score | Magnitude affects the result | Normalize or use cosine similarity when appropriate |
| Normalizing a zero vector | Division by zero is undefined | Handle zero norms explicitly |
Assuming x.T changes a 1D NumPy vector’s shape | A 1D array has only one axis | Use reshape(n, 1) or reshape(1, n) |
| Assuming multiplication order never matters | Matrix multiplication is generally noncommutative | Write transformations in the intended order |
| Treating a computed score as a trained model | A formula alone does not learn parameters | Separate 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
- If and , what are and ?
- Calculate the Euclidean norm of . What is its unit vector?
- Can a matrix multiply a matrix? What is the result’s shape?
- For and , why are
A * BandA @ Bdifferent? - What does
np.array([1, 2, 3]).T.shapereturn?
Show the worked answers
- The sum is . The dot product is .
- The norm is . The unit vector is .
- Yes. The inner dimensions are both , so the output shape is .
A * Bmultiplies corresponding entries and gives .A @ Bcomputes row-by-column dot products and gives .- It returns
(3,). Transposition does not change the shape of a one-dimensional NumPy array.
Related concepts and next reading
- AI Knowledge Map — Follow the complete learning sequence.
- Vectors and Matrices — Review coordinate representations, matrix shapes, and data matrices.
- Derivatives, Gradients, and the Chain Rule — Learn how training algorithms calculate changes in model parameters.
- Optimization and Gradient Descent — See how parameter vectors are updated to reduce error.
- NumPy, Arrays, and Tensors — Explore multidimensional numerical computation and broadcasting.
- Neural Network Fundamentals — Connect matrix multiplication with layers, weights, and activation functions.
- Embeddings and Vector Search — Apply vector similarity to semantic retrieval.
References
- MIT OpenCourseWare — 18.06SC Linear Algebra. Lectures, exercises, and explanations covering matrix operations, linear transformations, and vector spaces.
- NumPy documentation —
numpy.matmul. Matrix multiplication semantics and shape behavior. - NumPy documentation —
numpy.linalg.norm. Vector and matrix norm definitions used in numerical computing. - NumPy documentation — Broadcasting. How arrays of compatible shapes interact in element-wise operations.
Related articles in
- AI Agents and Tool-Using Workflows — Learn agent goals, tool invocation, planning, state, permissions, and how to evaluate multi-step AI workflows.
- AI Development Tools: Git, Jupyter, and APIs — Learn how Git, Jupyter notebooks, Python environments, and APIs fit together in reproducible, secure artificial intelligence workflows.
- How AI Is Changing Theoretical Computer Science — AI is beginning to help researchers explore algorithms, mathematical structures, and formal proofs. Here is what it can do, what still needs human judgment, and why verification matters.