Okay, let's put theory into practice. In the previous sections, we discussed different types of matrices like zero matrices, identity matrices, and diagonal matrices. Now, we'll see how straightforward it is to create these using NumPy. Remember, NumPy represents matrices as 2D arrays.
First, ensure you have NumPy imported, typically using the standard alias np
:
import numpy as np
The most fundamental way to create a matrix is from a Python list of lists. Each inner list represents a row.
# Create a 3x4 matrix (3 rows, 4 columns)
my_list = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
matrix_a = np.array(my_list)
print("Matrix A (from list of lists):")
print(matrix_a)
print("Shape of Matrix A:", matrix_a.shape)
print("Data type of Matrix A:", matrix_a.dtype)
Running this code will output:
Matrix A (from list of lists):
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
Shape of Matrix A: (3, 4)
Data type of Matrix A: int64
Notice how NumPy automatically determined the shape (3, 4)
and the data type (likely int64
or int32
depending on your system).
A zero matrix, denoted as O, contains only zeros. These are often used as initial placeholders. NumPy provides the np.zeros()
function. You need to provide the desired shape as a tuple (rows, columns).
# Create a 2x3 zero matrix
rows = 2
cols = 3
zero_mat = np.zeros((rows, cols))
print("\nZero Matrix (2x3):")
print(zero_mat)
print("Shape:", zero_mat.shape)
print("Data type:", zero_mat.dtype) # Defaults to float64
Output:
Zero Matrix (2x3):
[[0. 0. 0.]
[0. 0. 0.]]
Shape: (2, 3)
Data type: float64
By default, np.zeros()
creates floating-point numbers. If you need integers, specify the dtype
:
# Create a 3x3 zero matrix with integers
zero_mat_int = np.zeros((3, 3), dtype=int)
print("\nZero Matrix (3x3, Integer):")
print(zero_mat_int)
print("Data type:", zero_mat_int.dtype)
Output:
Zero Matrix (3x3, Integer):
[[0 0 0]
[0 0 0]
[0 0 0]]
Data type: int64
The identity matrix I is a square matrix (same number of rows and columns) with ones on the main diagonal and zeros everywhere else. It acts like the number 1 in matrix multiplication. NumPy has two common functions for this: np.identity()
and np.eye()
.
np.identity(n)
creates an n×n identity matrix.
# Create a 4x4 identity matrix using np.identity()
identity_mat = np.identity(4)
print("\nIdentity Matrix (4x4) using np.identity():")
print(identity_mat)
print("Shape:", identity_mat.shape)
print("Data type:", identity_mat.dtype) # Defaults to float64
Output:
Identity Matrix (4x4) using np.identity():
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
Shape: (4, 4)
Data type: float64
np.eye(N, M=None, k=0)
is more general. It creates an N×M matrix (if M is omitted, M=N, creating a square matrix). The argument k specifies the diagonal: k=0 is the main diagonal (default), k>0 is above the main diagonal, and k<0 is below. For a standard identity matrix, you usually just provide N.
# Create a 3x3 identity matrix using np.eye()
identity_mat_eye = np.eye(3)
print("\nIdentity Matrix (3x3) using np.eye():")
print(identity_mat_eye)
# Create a 3x5 matrix with ones on the main diagonal
eye_mat_rect = np.eye(3, 5)
print("\nRectangular Matrix (3x5) using np.eye():")
print(eye_mat_rect)
# Create a 4x4 matrix with ones on the diagonal above the main diagonal (k=1)
eye_mat_k1 = np.eye(4, k=1)
print("\nMatrix (4x4) using np.eye(k=1):")
print(eye_mat_k1)
Output:
Identity Matrix (3x3) using np.eye():
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
Rectangular Matrix (3x5) using np.eye():
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]]
Matrix (4x4) using np.eye(k=1):
[[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]
[0. 0. 0. 0.]]
For creating standard identity matrices, np.identity(n)
is perhaps slightly clearer, but np.eye(n)
works just as well.
A diagonal matrix has non-zero elements only on its main diagonal. NumPy's np.diag()
function is versatile. It can either extract the diagonal from an existing matrix or construct a square diagonal matrix from a 1D array (or list).
1. Constructing a Diagonal Matrix:
If you provide a 1D array (like a vector) to np.diag()
, it creates a square matrix where the elements of the array become the main diagonal.
# Define the diagonal elements
diagonal_values = [2, 5, -1, 3]
# Create a diagonal matrix from these values
diag_mat = np.diag(diagonal_values)
print("\nDiagonal Matrix constructed from [2, 5, -1, 3]:")
print(diag_mat)
print("Shape:", diag_mat.shape)
Output:
Diagonal Matrix constructed from [2, 5, -1, 3]:
[[ 2 0 0 0]
[ 0 5 0 0]
[ 0 0 -1 0]
[ 0 0 0 3]]
Shape: (4, 4)
2. Extracting a Diagonal:
If you provide a 2D array (a matrix) to np.diag()
, it extracts the main diagonal elements and returns them as a 1D array.
# Use the matrix_a we created earlier
print("\nOriginal Matrix A:")
print(matrix_a)
# Extract the main diagonal from matrix_a
diagonal_extracted = np.diag(matrix_a)
print("\nExtracted Diagonal from Matrix A:")
print(diagonal_extracted)
print("Shape:", diagonal_extracted.shape)
Output:
Original Matrix A:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
Extracted Diagonal from Matrix A:
[ 1 6 11]
Shape: (3,)
Note that the extracted diagonal only includes elements where the row index equals the column index (a11,a22,a33,...) up to the smaller dimension of the matrix.
These functions (np.array
, np.zeros
, np.identity
, np.eye
, np.diag
) provide the fundamental tools for creating the matrices you'll encounter frequently. Experiment with different shapes and data types to become comfortable with their usage. This foundation is essential for performing matrix operations, which we'll cover in the next chapter.
© 2025 ApX Machine Learning