Matrix Operations with NumPy Arrays

NumPy is a powerful library in Python that is widely used for numerical computing. It provides efficient and convenient operations for working with arrays, especially matrices. In this article, we will explore various matrix operations that can be performed using NumPy arrays.

Creating NumPy Arrays

Before diving into matrix operations, let's quickly review how to create NumPy arrays. We can create an array in NumPy using the numpy.array() function or by converting a native Python list using the numpy.asarray() function.

import numpy as np

# Create a NumPy array from a list
arr1 = np.array([[1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]])

# Create a NumPy array using numpy.asarray()
arr2 = np.asarray([1, 2, 3])

Now that we have our NumPy arrays, let's explore various matrix operations we can perform.

Matrix Addition and Subtraction

Matrix addition and subtraction can be performed element-wise by simply using the + and - operators. The matrices must have the same shape for addition and subtraction to work.

# Matrix addition
result1 = arr1 + arr1

# Matrix subtraction
result2 = arr1 - arr2

Matrix Multiplication

Matrix multiplication can be performed in two ways: element-wise multiplication and dot product multiplication.

For element-wise multiplication, we use the * operator. In this case, the shape of the matrices should be the same.

# Element-wise multiplication
result3 = arr1 * arr2

For dot product multiplication, we use the function or the @ operator. The number of columns in the first matrix should match the number of rows in the second matrix for dot product multiplication to work.

# Dot product multiplication
result4 =, arr1)
result5 = arr1 @ arr1

Matrix Transposition

To transpose a matrix, we use the numpy.transpose() function or the .T attribute.

# Transpose a matrix
result6 = np.transpose(arr1)
result7 = arr1.T

Matrix Inversion

To invert a square matrix, we use the numpy.linalg.inv() function.

# Matrix inversion
result8 = np.linalg.inv(arr1)

Other Operations

NumPy provides various other matrix operations like determinant calculation, eigenvalues, eigenvectors, and more. These operations can be performed using functions available in the numpy.linalg module.

# Calculate determinant
result9 = np.linalg.det(arr1)

# Calculate eigenvalues and eigenvectors
eigen_vals, eigen_vecs = np.linalg.eig(arr1)

These are just a few examples of the matrix operations that can be performed using NumPy arrays. NumPy provides numerous functions and methods to work with matrices and perform various computations efficiently.


In this article, we explored various matrix operations that can be performed using NumPy arrays. We discussed matrix addition, subtraction, multiplication, transposition, inversion, and other advanced operations. NumPy is a powerful tool for matrix computations and is widely used in the scientific and data analysis communities.

noob to master © copyleft