Python Numpy Matrix Multiplication

In this tutorial we will see python matrix multiplication using numpy (Numerical Python) library.

For using numpy you must install it first on your computer, you can use package manager like pip for installing numpy.

Numpy provide array data structure which is almost the same as python list but have faster access for reading and writing resulting in better performance. We will use numpy arrays to represent matrices.

To perform matrix multiplication of matrices a and b , the number of columns in a must be equal to the number of rows in b otherwise we cannot perform matrix multiplication.

We must check this condition otherwise we will face runtime error.

There is * operator for numpy arrays but that operator will not do matrix multiplication instead it will multiply the matrices element by element.

Here is an example with * operator:

# Import numpy 
import numpy as np

def printMatrix(a):
    
    # Printing matrix
    for i in range(0,len(a)):
        for j in range(0,len(a[0])):
            print(a[i][j],end = " ")
        print()

def main():
    
    # Declaring our matrices using arrays in numpy
    a = np.array([[1,2,3],[3,4,5],[5,6,7]])
    b = np.array([[1,2,3]])
    
    print("Matrix a :")
    printMatrix(a)
    print()
    
    print("Matrix b : ")
    printMatrix(b)
    print()
    
    # Using * operator to multiply
    c = a*b
    
    # Printing Result
    print("Result of a*b : ")
    printMatrix(c)

main()

Output:

Matrix a :
1 2 3
3 4 5
5 6 7

Matrix b :
1 2 3

Result of a*b :
1 4 9
3 8 15
5 12 21

Python Numpy Matrix Multiplication

We can see in above program the matrices are multiplied element by element. So for doing a matrix multiplication we will be using the dot function in numpy.

We can either write

  • np.dot(a,b)
  • a.dot(b)

for matrix multiplication here is the code:

# Import numpy 
import numpy as np

def printMatrix(a):
    
    # Printing matrix
    for i in range(0,len(a)):
        for j in range(0,len(a[0])):
            print(a[i][j],end = " ")
        print()
    
    

def main():
    
    # Taking rows and columns of a 
    m = int(input("Enter rows in a : "))
    n = int(input("Enter columns in a : "))
    
    # Taking rows and columns of b
    p = int(input("Enter rows in b : "))
    q = int(input("Enter columns in b : "))
    
    # Checking necessary condition for matrix multiplication
    if n!= p:
        print("Number of columns in b must be equal to rows in b")
        exit()
    
    # Initializing a and b list
    a = [ [0 for i in range(0,n)] for j in range(0,m) ]
    b = [ [0 for i in range(0,q)] for j in range(0,p) ]
    
    # Taking input list a
    print("Enter matrix a : ")
    for i in range(0,m):
        for j in range(0,n):
            a[i][j] = int(input("Enter element a[" + str(i) + "][" + str(j) + "] : "))
    
    # Taking input list b
    print("Enter matrix b : ")
    for i in range(0,p):
        for j in range(0,q):
            b[i][j] = int(input("Enter element b[" + str(i) + "][" + str(j) + "] : "))
    
    
    # Converting python list in numpy array
    a = np.array(a)
    b = np.array(b)
    
    print("Matrix a :")
    printMatrix(a)
    print()
    
    print("Matrix b : ")
    printMatrix(b)
    print()
    
    # Using dot operator to multiply
    c = a.dot(b)
    
    # Printing Result
    print("Result of a*b : ")
    printMatrix(c)


main()

Output:

Enter rows in a : 2
Enter columns in a : 3
Enter rows in b : 3
Enter columns in b : 2
Enter matrix a :
Enter element a[0][0] : 2
Enter element a[0][1] : 3
Enter element a[0][2] : 4
Enter element a[1][0] : 1
Enter element a[1][1] : 2
Enter element a[1][2] : 3
Enter matrix b :
Enter element b[0][0] : 4
Enter element b[0][1] : 5
Enter element b[1][0] : 1
Enter element b[1][1] : 6
Enter element b[2][0] : 9
Enter element b[2][1] : 7
Matrix a :
2 3 4
1 2 3

Matrix b :
4 5
1 6
9 7

Result of a*b :
47 56
33 38

Here the output is different because of the dot operator. Alternatively we can use the numpy matrices method to first convert the arrays into matrices and then use * operator to do matrix multiplication as below:

# Using * operator to multiply
c = np.matrix(a)*np.matrix(b)

Comment below if you have any queries related to python numpy matrix multiplication.

Leave a Comment

Your email address will not be published. Required fields are marked *