Linear Algebra Operations in NumPy (numpy.linalg Module)

The numpy.linalg module in NumPy provides various linear algebra functions essential for mathematical and engineering applications.

1. Importing NumPy

Before using NumPy's linear algebra functions, import the module.

            import numpy as np
        

2. Matrix Multiplication

Matrix multiplication is performed using np.matmul() or the @ operator.

            A = np.array([[1, 2], [3, 4]])
            B = np.array([[5, 6], [7, 8]])
            
            result = np.matmul(A, B)
            print(result)
            # Output:
            # [[19 22]
            #  [43 50]]
        

3. Matrix Inversion

The inverse of a matrix can be calculated using np.linalg.inv().

            A = np.array([[1, 2], [3, 4]])
            
            inverse_A = np.linalg.inv(A)
            print(inverse_A)
            # Output:
            # [[-2.   1. ]
            #  [ 1.5 -0.5]]
        

4. Determinant of a Matrix

The determinant of a matrix is computed using np.linalg.det().

            A = np.array([[1, 2], [3, 4]])
            
            determinant = np.linalg.det(A)
            print(determinant)  # Output: -2.0
        

5. Eigenvalues and Eigenvectors

Eigenvalues and eigenvectors of a matrix can be calculated using np.linalg.eig().

            A = np.array([[4, -2], [1, 1]])
            
            eigenvalues, eigenvectors = np.linalg.eig(A)
            print(eigenvalues)
            print(eigenvectors)
            # Example Output:
            # [3. 2.]
            # [[ 0.894  0.707]
            #  [ 0.447 -0.707]]
        

6. Solving Linear Equations

Linear equations of the form Ax = B can be solved using np.linalg.solve().

            A = np.array([[3, 1], [1, 2]])
            B = np.array([9, 8])
            
            x = np.linalg.solve(A, B)
            print(x)  # Output: [2. 3.]
        

Conclusion

The numpy.linalg module provides essential functions for performing linear algebra operations such as matrix multiplication, inversion, determinant calculation, eigenvalue computation, and solving linear equations.





Advertisement