matrix multiplication in Python

How to Implement Matrix Multiplication In Python

In this tutorial, you’ll learn how to implement matrix multiplication in Python. For implementing matrix multiplication you’ll be using numpy library.

Let’s get started by installing numpy in Python.

# install numpy using pip
pip install numpy

Once you have numpy installed, create a file called matrix.py.

Import the array from numpy inside matrix.py file.

# import array using numpy
from numpy import array

Using the array from numpy define your matrices as shown :

A = array([[1,2],[3,4]])
B = array([[5,6],[7,8]])

Element-wise Matrix Multiplication Using Python

To get the element-wise matrix multiplcation of matrices using Python you can use the multiply method provided by numpy module. Here is how you can use it :

import numpy as np
from numpy import array
A = array([[1,2],[3,4]])
B = array([[5,6],[7,8]])
print "-------- MATRIX A --------\n"
print A
print "\n"
print "-------- MATRIX B --------\n"
print B
print "\n"
print "-------- Element wise mutiplication Result ----------\n"
C = np.multiply(A,B)
print C

Save the above changes and execute the Python code. You will have the element wise multiplication result.

-------- MATRIX A --------

[[1 2]
 [3 4]]


-------- MATRIX B --------

[[5 6]
 [7 8]]


-------- Element wise mutiplication Result ----------

[[ 5 12]
 [21 32]]

Dot Product Of Matrix Using Python

For doing a Dot product on matrices using Python, you can utilize the dot method provided by numpy. Here is how you use it do implement Dot product of two matrices using Python.

import numpy as np
from numpy import array
A = array([[1,2],[3,4]])
B = array([[5,6],[7,8]])
print "-------- MATRIX A --------\n"
print A
print "\n"
print "-------- MATRIX B --------\n"
print B
print "\n"
print "-------- Dot Product Result ----------\n"
C = np.dot(A,B)
print C

Save the above changes and execute the Python code. You will have the Dot product printed in result.

-------- MATRIX A --------

[[1 2]
 [3 4]]


-------- MATRIX B --------

[[5 6]
 [7 8]]


-------- Dot Product Result ----------

[[19 22]
 [43 50]]