Skip to content
Related Articles

Related Articles

Matrix Multiplication in NumPy
  • Last Updated : 02 Sep, 2020

Let us see how to compute matrix multiplication with NumPy. We will be using the numpy.dot() method to find the product of 2 matrices.

For example, for two matrices A and B.
A = [[1, 2], [2, 3]]
B = [[4, 5], [6, 7]]

So, A.B = [[1*4 + 2*6, 2*4 + 3*6], [1*5 + 2*7, 2*5 + 3*7]
So the computed answer will be: [[16, 26], [19, 31]]

In Python numpy.dot() method is used to calculate the dot product between two arrays.

Example 1 : Matrix multiplication of 2 square matrices.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing the module
import numpy as np
  
# creating two matrices
p = [[1, 2], [2, 3]]
q = [[4, 5], [6, 7]]
print("Matrix p :")
print(p)
print("Matrix q :")
print(q)
  
# computing product
result = np.dot(p, q)
  
# printing the result
print("The matrix multiplication is :")
print(result)

chevron_right


Output :

Matrix p :
[[1, 2], [2, 3]]
Matrix q :
[[4, 5], [6, 7]]
The matrix multiplication is :
[[16 19]
 [26 31]]

Example 2 : Matrix multiplication of 2 rectangular matrices.



filter_none

edit
close

play_arrow

link
brightness_4
code

# importing the module
import numpy as np
  
# creating two matrices
p = [[1, 2], [2, 3], [4, 5]]
q = [[4, 5, 1], [6, 7, 2]]
print("Matrix p :")
print(p)
print("Matrix q :")
print(q)
  
# computing product
result = np.dot(p, q)
  
# printing the result
print("The matrix multiplication is :")
print(result)

chevron_right


Output :

Matrix p :
[[1, 2], [2, 3], [4, 5]]
Matrix q :
[[4, 5, 1], [6, 7, 2]]
The matrix multiplication is :
[[16 19  5]
 [26 31  8]
 [46 55 14]]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :