Identity and Diagonal Matrices in NumPy

NumPy provides functions to create identity matrices and extract or create diagonal matrices. The primary functions used for these operations are:

  • eye() - Creates an identity matrix.
  • diag() - Extracts or creates a diagonal matrix.

1. Creating an Identity Matrix (eye)

The eye() function generates an identity matrix, where all diagonal elements are 1, and the rest are 0.

    import numpy as np
    
    identity_matrix = np.eye(4)
    print(identity_matrix)
        

Output:

    [[1. 0. 0. 0.]
     [0. 1. 0. 0.]
     [0. 0. 1. 0.]
     [0. 0. 0. 1.]]
        

2. Extracting the Diagonal of a Matrix (diag)

The diag() function extracts the diagonal elements from an existing matrix.

    arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    diagonal_elements = np.diag(arr)
    print(diagonal_elements)
        

Output:

    [1 5 9]
        

3. Creating a Diagonal Matrix

The diag() function can also create a diagonal matrix from a given list or array.

    diagonal_matrix = np.diag([10, 20, 30])
    print(diagonal_matrix)
        

Output:

    [[10  0  0]
     [ 0 20  0]
     [ 0  0 30]]
        

Conclusion

Using eye() and diag() in NumPy, we can efficiently create identity matrices and work with diagonal elements. These functions are useful in linear algebra and numerical computations.





Advertisement