NumPy dot() function

The dot() function is mainly used to calculate the dot product of two vectors.

  • This function can handle 2D arrays but it will consider them as matrix and will then perform matrix multiplication.
  • In the case, if an array a is an N-D array and array b is an M-D array (where, M >= 2) then it is a sum product over the last axis of a and the second-to-last axis of b:
dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])

Syntax of numpy.dot():

The syntax required to use this function is as follows:

numpy.dot(a, b, out=None)

Parameters:

Let us discuss the parameters of this function:

  • a
    This is the first parameter. If “a” is complex number then its complex conjugate is used for the calculation of the dot product.
  • b
    This is the second parameter. If “b” is complex then its complex conjugate is used for the calculation of the dot product.
  • out
    This indicates the output argument. This out must have the exact kind that would be returned if it was not used. Otherwise it must be C-contiguous and its dtype must be the dtype that would be returned for dot(a, b).

Returned Values:

The dot() function will return the dot product of a and b. If both a and b are scalars or if both are 1-D arrays then a scalar value is returned, otherwise an array is returned. If out is given, then it is returned.

Note: The ValueError is raised in the case if the last dimension of a is not the same size as the second-to-last dimension of b.

Example 1:

The code snippet is as follows where we will use dot() function:

import numpy as np

#Let us take scalars first 
a = np.dot(8, 4) 
print("The dot Product of above given scalar values : ")
print(a) 

# Now we will take 1-D arrays 
vect_a = 4 + 3j
vect_b = 8 + 5j

dot_product = np.dot(vect_a, vect_b) 
print("The Dot Product of two 1-D arrays is : ")
print(dot_product) 

Output:


The dot Product of above given scalar values :
32
The Dot Product of two 1-D arrays is :
(17+44j)

Explanation of the calculation of dot product of two 1D Arrays:

vect_a = 4+ 3j
vect_b = 8 + 5j

Now calculating the dot product:
= 4(8 + 5j) + 3j(8 – 5j)
= 32+ 20j + 24j – 15
= 17 + 44j

Example 2:

Now let’s create two numpy arrays and then find the dot product for them using the dot() function:

import numpy as np

a = np.array([[50,100],[12,13]])  
print("The Matrix a is:")
print (a)

b = np.array([[10,20],[12,21]])  
print("The Matrix b is :")
print(b)

dot = np.dot(a,b)  
print("The dot product of a and b is :")
print(dot)

Output:

Numpy dot() function example
Follow Us On