An AI model cannot work directly with an abstract idea such as a student’s study habits or the meaning of a sentence. It needs a computational representation. Vectors and matrices provide two of the most important mathematical structures for representing numerical information, organizing examples, and describing calculations in machine learning.
They belong to linear algebra, the branch of mathematics that studies vectors, vector spaces, linear transformations, and related systems. This article introduces what vectors and matrices are, how to read them, and where they appear in AI. Their arithmetic, including dot products and matrix multiplication, is developed separately in Vector and Matrix Operations.
Begin with three numbers about one student
Suppose an educational application records a student’s weekly study time, completed practice questions, and quiz score:
- Study time: 6 hours
- Practice questions: 18
- Quiz score: 80 points
We could keep these as three separate variables. But machine-learning software usually needs a consistent way to represent many values together. One choice is an ordered vector:
The order matters. If the model expects hours, practice questions, score, then describes something different. The numbers also have different units, so using them directly in a distance calculation might be misleading without appropriate scaling.
Now record the same features for three students:
This is a matrix with three rows and three columns. In this example, every row is one student and every column is one feature. The shape is . The same number of rows and columns is a coincidence: a dataset of 500 students with three features would have shape .
A scalar is simpler still: it is one number, such as the value .
These three ideas form a useful ladder: scalar → vector → matrix. The rest of the article makes each definition precise, explains how to read mathematical notation, and shows how these structures become NumPy arrays.
Scalars, vectors, and matrices
A scalar is a single value from a number system, typically a real number in introductory AI calculations. A vector is an element of a vector space; once a coordinate system is chosen, it can often be represented by an ordered list of numbers. A matrix is a rectangular arrangement of entries in rows and columns. Matrices can store collections of vectors or represent linear transformations.
| Mathematical object | Example | What to notice |
|---|---|---|
| Scalar | One value. | |
| Vector | An ordered collection of three coordinates. | |
| Matrix | Three rows and two columns. |
These are mathematical objects, not simply different ways of displaying numbers. Their structure determines which computations make sense. For example, the order of a vector’s coordinates matters, and a matrix’s number of rows and columns affects which matrices and vectors it can be multiplied by.
Terminology: A vector is more general than a numerical list. In linear algebra, vectors can also be functions, polynomials, or other objects that satisfy the rules of a vector space. For the first stage of AI study, we mainly use vectors with real-number coordinates.
Understanding vectors
A numerical vector is a mathematical object represented by an ordered sequence of coordinates. In AI, those coordinates can represent measurable input features, learned model parameters, or an embedding produced by a model.
For example, suppose a student is described using three features:
- Hours studied in a week:
- Practice exercises completed:
- Previous quiz score out of :
We can write the feature vector as:
The vector has three coordinates, so it belongs to the three-dimensional real coordinate space . In notation, .
The values have meaning only because we specify what each coordinate represents and in what order. The vector is not interchangeable with when the first coordinate is supposed to mean study hours.
Vectors as geometric objects
In two or three dimensions, a vector can be visualized as an arrow. Its coordinates describe a displacement relative to a chosen coordinate system. A vector such as:
can be drawn as an arrow from the origin to the point . This is a useful geometric interpretation, even though the same mathematical idea extends to spaces that we cannot draw directly.
This picture does not mean every AI vector is a physical direction. A feature vector may combine quantities with different units, such as hours, scores, and counts. In that case, the arrow is a mathematical analogy; its coordinates primarily represent measured or learned quantities.
Components and dimensionality
For a vector with coordinates, we write:
Here, is the th component, and is the number of coordinates in the chosen representation.
- Two-dimensional vector: has two coordinates.
- Three-dimensional vector: has three coordinates.
- High-dimensional vector: A text embedding might have hundreds or thousands of coordinates, depending on the model.
The dimensionality of a numerical vector describes how many coordinates are needed to represent it in the chosen coordinate system. It is not the same as the number of axes in a NumPy array, a distinction we will examine later.
Row vectors and column vectors
Vectors are often written vertically as column vectors:
A row vector has its entries on one line:
The superscript denotes transpose, an operation that switches rows and columns. A three-component column vector has shape ; the corresponding row vector has shape .
In introductory linear algebra, column vectors are a common default. In machine-learning software, a single example may instead be stored as a one-dimensional array or a row of a data matrix. Always check the convention used by a formula or library rather than assuming they are identical.
Understanding matrices
A matrix is a rectangular array of elements arranged in rows and columns. For instance:
Matrix has two rows and three columns. Its order, or shape, is , read as “two by three.” The mathematical notation says that is a real-valued matrix with that shape.
For a general matrix with rows and columns:
The entry is the element in row and column . In the earlier example, because is in the second row and third column. Mathematical subscripts here begin at ; Python array indices begin at .
Rows, columns, and shape
A matrix can be viewed in two complementary ways:
- Each row is a row vector, often representing one observation or example in a dataset.
- Each column is a column vector, often collecting one feature across multiple observations.
A matrix with rows and columns contains entries. For example, a matrix contains elements, even though it has only two axes: rows and columns.
The word dimension can therefore be ambiguous. In ordinary linear algebra, “a vector in ” means three coordinates. In NumPy, “an array with two dimensions” means an array with two indexing axes. When precision matters, use vector length, matrix shape, or array axis count.
Some matrix types worth recognizing
| Matrix type | Defining property | Example or use |
|---|---|---|
| Rectangular matrix | Rows and columns may differ in number. | Dataset with 100 examples and 8 features: . |
| Square matrix | Same number of rows and columns. | A transformation matrix. |
| Zero matrix | Every entry is zero. | An additive identity for matrices of the same shape. |
| Identity matrix | Square matrix with ones on the main diagonal and zeros elsewhere. | Leaves compatible vectors unchanged under multiplication. |
| Diagonal matrix | All entries away from the main diagonal are zero. | Scaling different coordinates separately. |
| Sparse matrix | Most entries are zero. | Large user-item or document-term representations. |
These types are not exclusive: an identity matrix is also square, diagonal, and sparse in many practical settings.
How a dataset becomes a matrix
Imagine a small dataset recording students’ weekly study hours and the number of practice sets they completed.
| Student | Study hours | Practice sets |
|---|---|---|
| A | 2 | 1 |
| B | 4 | 3 |
| C | 5 | 4 |
If each student is an example and each measured quantity is a feature, the feature matrix is:
The shape of is :
- rows = examples or samples.
- columns = input features per example.
This convention is widely used in tabular machine learning, including common interfaces in scikit-learn. It is a convention, not an unavoidable mathematical law: another system could store samples in columns, provided all its formulas and code are consistent.
Features are not labels
If the goal is to predict whether each student will pass an exam, the actual outcomes are usually stored separately as a target vector. Suppose the observed outcomes are:
Here means did not pass and means passed. The input matrix and the targets describe different things:
- contains information used to make predictions.
- contains the known answers used during supervised training or evaluation.
The th row of corresponds to the th entry of . That alignment must be preserved when sorting, filtering, or splitting data. For more on those processes, see Data Preparation and Data Leakage and Machine Learning Paradigms.
Note: A real dataset may include categorical values, missing entries, different scales, or non-numerical content. Additional preprocessing is often necessary before a learning algorithm can use the data. Representing values in a matrix does not make them automatically suitable for training.
Why vectors and matrices matter in AI
Vectors and matrices are useful because they provide a consistent way to store quantities and express operations on many values. Their roles appear throughout AI, not only in linear regression.
1. Input features and model parameters
For tabular data, a vector represents one example and a matrix represents many examples. A model may also store its weights as a vector or matrix. The weights determine how strongly different inputs influence its calculations.
For example, a model with two numerical inputs may use a weight vector:
These are example parameter values, not a trained or meaningful model by themselves. Combining weights with inputs requires vector operations, which are explained in the next article.
2. Neural network layers
A fully connected neural network layer usually applies a learned linear or affine transformation to its input, followed by an optional activation function. The transformation is described using a weight matrix and often a bias vector.
If an input has features and a layer produces output features, the corresponding weight matrix can be represented with shape under a row-sample convention. Other textbooks and software use the transposed orientation. The dimensions must agree with the chosen representation.
The structure becomes easier to understand when you know what rows, columns, and shapes mean. The actual calculations are covered in Neural Network Fundamentals.
3. Embeddings
An embedding is a numerical representation that places an item, such as a word, sentence, image, or user, into a vector space. Its coordinates are learned or constructed to capture information useful for a task.
For example, a language model might represent each token using a vector with hundreds of coordinates. An embedding is not simply a manually constructed list of descriptive words; its coordinates often have no simple, individually readable meaning.
Embeddings support applications such as semantic search and recommendation. Their similarity can be measured using operations such as dot products or cosine similarity. See Embeddings and Vector Search.
4. Digital images and other structured data
A grayscale image can be represented as a two-dimensional array of intensity values, with height and width as its axes. A color image commonly adds a channel axis, such as red, green, and blue, making the representation three-dimensional.
For example, an image with 28 rows and 28 columns can be stored as an array of shape . An RGB image might have shape in a height-width-channel convention. Libraries can use different axis orders, such as , so shapes must be read in context.
Higher-dimensional arrays often appear in deep learning to represent batches, sequences, image channels, and more. They are commonly called tensors in AI libraries; the mathematical concept of a tensor is broader and has additional structure beyond its array shape.
From mathematics to NumPy arrays
NumPy is a Python library for numerical computing. Its ndarray structure stores arrays with one or more axes. NumPy arrays are widely used to represent vectors and matrices computationally.
Consider three representations of the same three numbers:
import numpy as np
flat = np.array([2, 5, 7])
column = np.array([[2], [5], [7]])
row = np.array([[2, 5, 7]])
print(flat.shape) # (3,)
print(column.shape) # (3, 1)
print(row.shape) # (1, 3)
print(flat.ndim) # 1
print(column.ndim) # 2
print(row.ndim) # 2
All three containers hold three values, but their shapes are different:
| NumPy array | Shape | Axes | Interpretation |
|---|---|---|---|
flat | (3,) | 1 | One-dimensional array with three entries. |
column | (3, 1) | 2 | Two-dimensional array arranged as a column. |
row | (1, 3) | 2 | Two-dimensional array arranged as a row. |
This matters because numerical libraries use shapes to decide how operations are performed. In particular, the transpose of a one-dimensional NumPy array still has shape (3,); it does not automatically become a two-dimensional column or row.
import numpy as np
flat = np.array([2, 5, 7])
print(flat.T.shape) # (3,)
print(flat.reshape(3, 1).shape) # (3, 1)
print(flat.reshape(1, 3).shape) # (1, 3)
Reading a matrix in code
The mathematical matrix:
can be represented as follows:
import numpy as np
A = np.array([
[2, 4, 6],
[1, 3, 5],
])
print(A.shape) # (2, 3)
print(A.ndim) # 2
print(A.size) # 6
print(A[1, 2]) # 5 (second row, third column)
print(A[0]) # [2 4 6] (first row)
print(A[:, 1]) # [4 3] (second column)
Notice the indexing difference: mathematical becomes A[1, 2] in Python. Both access the value .
Worked example: feature matrix and target vector
The earlier student dataset can be created directly in NumPy:
import numpy as np
# Rows are students. Columns are study hours and practice sets.
X = np.array([
[2, 1],
[4, 3],
[5, 4],
], dtype=float)
# Each target corresponds to the student in the same row of X.
y = np.array([0, 1, 1], dtype=int)
n_samples, n_features = X.shape
print("samples:", n_samples) # 3
print("features:", n_features) # 2
print("first student:", X[0]) # [2. 1.]
print("study-hours column:", X[:, 0]) # [2. 4. 5.]
print("targets:", y) # [0 1 1]
assert X.shape == (3, 2)
assert y.shape == (3,)
assert X.shape[0] == y.shape[0]
This code organizes data; it does not train an AI model. That distinction is fundamental. Before learning, a program must know what each observation contains, where its features are stored, and how the target outcomes correspond to the examples.
Common misconceptions
| Misconception | More accurate understanding |
|---|---|
| “A vector is just any Python list.” | A list can represent a numerical vector, but the vector is a mathematical object with defined operations and structure. |
| “A vector always points in physical space.” | An arrow is useful in low dimensions; feature vectors and embeddings may describe abstract quantities. |
| “A matrix is only a table of data.” | Matrices can store data but also represent linear maps and systems of equations. |
| “A three-component vector must be a 3D NumPy array.” | A length-three numerical vector is commonly stored in a NumPy array with shape (3,), which has one array axis. |
| “Rows always represent samples.” | That is a frequent ML convention, not a rule of linear algebra. |
| “A model learns because the input is a matrix.” | A matrix stores or structures values; a learning algorithm and training objective are still required. |
| “Two arrays with the same number of elements are interchangeable.” | Different shapes can behave differently under multiplication, broadcasting, and indexing. |
Check your understanding
Try these questions before expanding the answers.
- A dataset has examples and numerical features per example. What is the shape of its feature matrix if samples occupy rows?
- In , what is the value of ? How do you access it in NumPy?
- What is the difference between a vector with four coordinates and a NumPy array that has four axes?
- If
np.array([4, 7, 9]).Tis evaluated, will the result have shape(3, 1)?
Show the worked answers
- The shape is , or
(120, 8)in NumPy. There are 120 sample rows and 8 feature columns. - The value is . Mathematically it is row 2, column 3; in NumPy it is
B[1, 2]because Python indexing starts at zero. - Four coordinates describe the length of the mathematical vector’s coordinate representation. Four array axes describe the shape structure of a computational array, such as a tensor of shape
(2, 3, 4, 5). - No. The transpose of a one-dimensional NumPy array stays one-dimensional, with shape
(3,). Use.reshape(3, 1)for an explicit two-dimensional column array.
Related concepts and next reading
- AI Knowledge Map — Return to the broader learning sequence.
- Vector and Matrix Operations — Learn addition, dot products, norms, matrix multiplication, and transpose.
- Derivatives, Gradients, and the Chain Rule — Learn how changes in mathematical quantities support model training.
- Python for Artificial Intelligence — Practice with Python and numerical libraries.
- Feature Engineering, Encoding, and Scaling — Understand how raw information becomes useful numerical features.
- Neural Network Fundamentals — See how layers use vectors, matrices, and learnable parameters.
- Embeddings and Vector Search — Understand learned vector representations and similarity-based retrieval.
References
- MIT OpenCourseWare — 18.06SC Linear Algebra. University-level material on vectors, matrices, linear equations, and transformations.
- NumPy documentation — The N-dimensional array. Definitions of array shapes, dimensions, indexing, and element types.
- NumPy documentation — Absolute basics for beginners. Introductory examples for constructing arrays and inspecting their shapes.
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.