Python NumPy Matrix Operations

In this Python NumPy tutorial, I will explain what different Python NumPy matrix operations are, exploring the various functions and methods that make matrix computations not just possible but also efficient and straightforward.

Different operations on Python NumPy matrix can be addition through add() or + operator, subtraction through subtract() or – operator, multiplication by dot() or * operator, division by divide() function, or we can transpose a matrix by .T or .transpose, inverse by linalg.inv(), and power by linalg.matrix_power().

Python NumPy Matrix Operations

The operation on the matrix in Python matrix can be divided into two different categories:

  1. Basic Matrix Operations
    • Addition
    • Subtraction
    • Multiplication
    • Division
  2. Advanced Matrix Operations
    • Transpose
    • Inverse
    • Power

Let’s see them one by one in detail with some illustrative examples:

Matrix Addition in Python using NumPy

Matrix addition is a fundamental operation where two matrices of the same dimensions are added together by adding their corresponding elements through Python NumPy. We will use the add() function from the NumPy library to add the two matrices in Python.

Example: Consider a situation where we have to add two matrices of the same size through Python,

import numpy as np

day1_sales = np.array([[10, 20, 30]])
day2_sales = np.array([[15, 25, 35]])
total_sales = np.add(day1_sales, day2_sales)
print("Total sales over two days in each city:", total_sales)

Output: The output of the above code is:

Total sales over two days in each city: [[25 45 65]]
python numpy matrix addition operation

This way the Python NumPy matrix operations of addition through the add() function in Python.

Note: We can simply use the + operator to add two matrices in Python.

Python NumPy Matrix Subtraction Operations

The condition for the subtraction of matrices is similar to the addition operation, which means the matrices need to be of the same size. The subtract() function from the NumPy library in Python can help us to find the difference between two matrices.

Example: Let’s find the difference between two matrices through Python.

import numpy as np

day1_sales = np.array([[10, 20, 30]])
day2_sales = np.array([[14, 40, 10]])
profit = np.subtract(day2_sales, day1_sales)
print("Total profit in each sales category in two days:", profit)

Output: The implementation of the code is:

Total profit in each sales category in two days: [[  4  20 -20]]
np.matrix subtraction operation in Python

The Python NumPy matrix operation of subtraction through the subtract() function in NumPy.

Note: We can simply use the – operator to subtract two matrices in Python.

Matrix Multiplication in Python NumPy

Matrix multiplication in Python NumPy, also known as the dot product for two-dimensional arrays, is not the same as element-wise multiplication. So, we will use the dot() function, which takes two matrices as input and produces a single matrix in Python.

The only condition required is that the number of columns in the first matrix must be equal to the number of rows in the second matrix in Python

Example 1: Let’s take two matrices and multiply them element-wise through the dot() function in Python.

import numpy as np
units_sold = np.array([
    [30, 40],
    [50, 60],
    [70, 80]
])
pricing = np.array([
    [10, 15, 20],
    [22, 27, 30]
])
total_sales = np.dot(units_sold, pricing)
print("Total sales matrix:\n", total_sales)

Output: The implementation of the Python code is:

Total sales matrix:
 [[1180 1530 1800]
 [1820 2370 2800]
 [2460 3210 3800]]
np.dot in python

Example 2: We can also do scalar multiplication operations on the Python NumPy matrix.

The scalar multiplication operation means multiplying each and every element of the NumPy matrix with a number. We can do this operation using the * operator in Python.

import numpy as np
distances_miles = np.array([[0, 2451, 789],
                            [2451, 0, 1745],
                            [789, 1745, 0]])
miles_to_km = 1.60934
distances_km = distances_miles * miles_to_km
print("Distances in Kilometers:\n", distances_km)

Output: The implementation of the above Python code with a screenshot:

Distances in Kilometers:
 [[   0.      3944.49234 1269.76926]
 [3944.49234    0.      2808.2983 ]
 [1269.76926 2808.2983     0.     ]]
python matrix multiplication

This way in Python NumPy matrix operations of multiplication are done by the dot() function and the * operator.

Matrix division operation in Python

There is an operation involving the division of two matrices using the np.divide() function from the NumPy library in Python.

This function is called with two arguments, which are expected to be arrays (or anything that can be converted to arrays) of the same shape. The divide() function performs element-wise division between the two arrays, meaning that each element in an array is divided by the corresponding element of another array in Python.

Example: Let’s two arrays and try to apply the division operation on them through Python.

import numpy as np

expenses_a = np.array([200, 400])
expenses_b = np.array([150, 300])

expense_ratio = np.divide(expenses_a, expenses_b)
print("Expense Ratio of Household A to B:\n", expense_ratio)

Output: The implementation of the code in Python Pycharm editor:

Distances in Kilometers:
 [[   0.      3944.49234 1269.76926]
 [3944.49234    0.      2808.2983 ]
 [1269.76926 2808.2983     0.     ]]
numpy matrix operations in Python

This way we can do the Python NumPy matrix operations of division through the divide() function.

Transpose Matrix NumPy Operation in Python

Transposing a matrix means flipping a matrix over its diagonal. Rows become columns and vice versa. NumPy provides the .transpose() method or the .T attribute to transpose matrices in Python.

Example: Here, we have a matrix in Python and we want to transpose it and get a new matrix in Python.

import numpy as np

data = np.array([
    [10, 20, 30],
    [40, 50, 60],
    [70, 80, 90]
])
transposed_data = data.T
print("Transposed matrix (States as columns):\n", transposed_data)

Output: The implementation of the code in Python with screenshot:

Transposed matrix (States as columns):
 [[10 40 70]
 [20 50 80]
 [30 60 90]]
numpy transpose matrix in Python

To transpose a Python NumPy matrix, we can use .T or .transpose() function in Python.

Matrix manipulation in Python by Inverse operation

The inverse of a matrix is a matrix that, when multiplied with the original matrix, results in the identity matrix. In Python, the NumPy library provides a straightforward method to compute the inverse of a matrix using the numpy.linalg.inv() function.

Example: Let’s take a matrix and try to inverse it through Python.

import numpy as np

A = np.array([[1, 9, 8],
              [4, 5, 11],
              [7, 6, 3]])

A_inv = np.linalg.inv(A)
print("The inverse of the matrix A is:\n", A_inv)

Output: The implementation of the Python code:

The inverse of the matrix A is:
 [[-0.11434978  0.0470852   0.132287  ]
 [ 0.14573991 -0.11883408  0.0470852 ]
 [-0.02466368  0.12780269 -0.06950673]]
numpy matrix inverse operation in Python

To inverse a Python NumPy matrix, we can use np.linalg.inv() function.

NumPy Matrix power operation in Python

Matrix power is an operation in mathematics where a matrix is multiplied by itself a certain number of times. In Python, this can be done easily using the NumPy library, which provides a function called numpy.linalg.matrix_power() for this purpose.

Example: Let’s take a matrix in Python and find its square through Python.

import numpy as np

migration_matrix = np.array([[1, 2, 3],
                             [4, 5, 6],
                             [7, 8, 9]])
two_year_migration = np.linalg.matrix_power(migration_matrix, 2)
print("The power of the matrix is:\n" ,two_year_migration)

Output: The implementation of the Python code is:

The power of the matrix is:
 [[ 30  36  42]
 [ 66  81  96]
 [102 126 150]]
matrix Power operations in python

To find the power of a Python NumPy matrix, we can use np.linalg.matrix_power() function.

Conclusion

In conclusion, understanding and utilizing Python NumPy matrix operations like addition, subtraction, multiplication, division, transpose, inverse, and power with add(), subtract(), divide(), dot() or * operator, .transpose or .T, linalg.inv(), and linalg.matrix_power() function respectively can greatly enhance one’s capability to process and analyze data effectively.

You may like the following Python tutorials: