Numpy `dot()`

function is used to perform matrix multiplication.

You might be thinking if you can multiply two arrays then why there is a need for the `dot()`

function. Let's understand why direct multiplication of arrays does not work:

import numpy as np a = np.array([[1, 2], [3, 4]]) b = np.array([[5, 10], [15, 20]]) c = a*b print('Matrix a:\n', a) print('Matrix b:\n', b) print('Resultant Matrix:\n ', c)

Output

Matrix a: [[1 2] [3 4]] Matrix b: [[ 5 10] [15 20]] Resultant Matrix: [[ 5 20] [45 80]]

**Note:** Following tutorials are essential to improve your understanding of performing various matrix operations in NumPy:

- If you want to learn how to create a matrix in NumPy, then visit How to use NumPy matrix() in Python?
- If you are interested in learning how to perform transpose of a matrix, then visit How to use NumPy transpose() in Python?

As you can see direct multiplication of two NumPy arrays does not produce the desired result. It is just multiplying corresponding elements of two arrays. That is why `dot()`

function is introduced.

Let's see the syntax of `dot()`

function:

np.dot(a, b)

Both `a`

and `b`

parameter refer to two-dimensional Numpy array.

**Note**: Before you perform matrix multiplication, make sure that the number of columns in the first matrix is equal to the number of rows in the second matrix.

#Python program to test np.dot() function import numpy as np a = np.array([[1, 2], [3, 4]]) b = np.array([[5, 10], [15, 20]]) c = np.dot(a, b) print('Matrix a:\n', a) print('Matrix b:\n', b) print('Resultant Matrix:\n ', c)

Output

Matrix a: [[1 2] [3 4]] Matrix b: [[ 5 10] [15 20]] Resultant Matrix: [[ 35 50] [ 75 110]]

- How to use NumPy sum() in Python?
- How to use NumPy max() in Python?
- How to use NumPy min() in Python?
- How to use NumPy mean() in Python?
- How to use NumPy average() in Python?