
Beyond the common square and rectangular types, there are special matrices that serve unique purposes in mathematical computations and applications. The identity, zero, and diagonal matrices are three such types, each with distinct computational use cases.
Creating an Identity Matrix
An identity matrix is a square matrix in which all the elements of the principal diagonal are ones, and all other elements are zeros.
Here’s how you can create an identity matrix using NumPy:
import numpy as np
# Create a 3x3 identity matrix
identity_matrix = np.eye(3)
print("Identity Matrix:\n", identity_matrix)
print("The shape of this Identity Matrix is", identity_matrix.shape)
Output:
Identity Matrix: [[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]] The shape of this Identity Matrix is (3, 3)
Creating a Zero Matrix
A zero matrix is any matrix in which all elements are zero. These matrices can be of any size, and are particularly useful in various algebraic operations.
Below is how you can create a 2×3 zero matrix using NumPy:
import numpy as np
# Create a 2x3 zero matrix
zero_matrix = np.zeros((2, 3))
print("Zero Matrix:\n", zero_matrix)
print("The shape of this Zero Matrix is", zero_matrix.shape)
Output:
Zero Matrix: [[0. 0. 0.] [0. 0. 0.]] The shape of this Zero Matrix is (2, 3)
To illustrate further, here’s how you can create a square zero matrix:
import numpy as np
# Create a 3x3 square zero matrix
square_zero_matrix = np.zeros((3, 3))
print("Square Zero Matrix:\n", square_zero_matrix)
print("The shape of this Square Zero Matrix is", square_zero_matrix.shape)
Output:
Square Zero Matrix: [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]] The shape of this Square Zero Matrix is (3, 3)
Creating a Diagonal Matrix
A diagonal matrix is one where all entries outside the main diagonal are zero. The diagonal itself can contain any numbers. Here’s how to create a diagonal matrix with predefined diagonal values:
import numpy as np
# Create a diagonal matrix with diagonal entries 1, 2, and 3
diagonal_matrix = np.diag([1, 2, 3])
print("Diagonal Matrix:\n", diagonal_matrix)
print("The shape of this Diagonal Matrix is", diagonal_matrix.shape)
Output:
Diagonal Matrix: [[1 0 0] [0 2 0] [0 0 3]] The shape of this Diagonal Matrix is (3, 3)
The .shape attribute confirms that the matrix is square, which is typical for diagonal matrices.
By understanding how to construct identity, zero, and diagonal matrices, you are better prepared to tackle more complex linear algebra tasks. It’s important to note that while identity and diagonal matrices are inherently square due to their definitions, zero matrices can be of any shape—either square or rectangular. This flexibility allows zero matrices to be particularly versatile in various algebraic operations.
