Just as we used NumPy arrays to represent vectors in Python, we'll use them for matrices too. While vectors were conveniently represented by one-dimensional (1D) arrays, matrices, being rectangular grids of numbers with rows and columns, naturally map to two-dimensional (2D) NumPy arrays.
numpy.array
The most straightforward way to create a matrix is by passing a list of lists to the numpy.array()
function. Each inner list represents a row in the matrix.
Let's say we want to represent the following 2×3 matrix (2 rows, 3 columns):
A=[142536]In Python using NumPy, we would create it like this:
import numpy as np
# Create a 2x3 matrix from a list of lists
A = np.array([
[1, 2, 3], # First row
[4, 5, 6] # Second row
])
print(A)
The output will show the NumPy array representation:
[[1 2 3]
[4 5 6]]
Notice how the structure directly mirrors the mathematical notation: the outer list contains two inner lists, corresponding to the two rows, and each inner list contains three elements, corresponding to the three columns.
Just like with vectors, understanding the dimensions (or "shape") of a matrix is important, especially when we get to operations like matrix multiplication. NumPy arrays have a convenient .shape
attribute that returns a tuple representing the dimensions. For a 2D array (matrix), the tuple will be (number_of_rows, number_of_columns)
.
Let's check the shape of the matrix A
we just created:
# Get the dimensions (shape) of matrix A
print(A.shape)
The output will be:
(2, 3)
This confirms that A
is indeed a 2×3 matrix.
Let's create a 3×3 square matrix (where the number of rows equals the number of columns):
B=963852741Using NumPy:
# Create a 3x3 matrix
B = np.array([
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
])
print("Matrix B:")
print(B)
# Check its shape
print("\nShape of B:")
print(B.shape)
Output:
Matrix B:
[[9 8 7]
[6 5 4]
[3 2 1]]
Shape of B:
(3, 3)
As expected, the shape is (3, 3)
.
It's worth noting that while we often represent vectors using 1D NumPy arrays (like np.array([1, 2, 3])
with shape (3,)
), they can also be explicitly represented as matrices with either one column (a column vector) or one row (a row vector).
Column Vector (e.g., 3×1):
col_vector = np.array([
[1],
[2],
[3]
])
print("Column Vector:\n", col_vector)
print("Shape:", col_vector.shape) # Output: (3, 1)
Row Vector (e.g., 1×3):
row_vector = np.array([
[1, 2, 3]
])
print("\nRow Vector:\n", row_vector)
print("Shape:", row_vector.shape) # Output: (1, 3)
This distinction between a 1D array (shape (n,)
) and a 2D array with one dimension being 1 (shape (n, 1)
or (1, n)
) becomes significant in certain NumPy operations, particularly those involving matrix multiplication. For now, the main takeaway is that general matrices are represented as 2D NumPy arrays, created typically from lists of lists.
With this ability to represent matrices in Python, we are ready to explore different types of specialized matrices you'll often encounter.
© 2025 ApX Machine Learning