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:

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:

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:

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 *