NumPy - dot() function
The NumPy dot() function is used to perform dot product of two arrays. Specifically,
- If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation).
- If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred.
- If either a or b is 0-D (scalar), it is equivalent to multiply and using numpy.multiply(a, b) or a * b is preferred.
- If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.
- If a is an N-D array and b is an M-D array (where M>=2), 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
numpy.dot(a, b, out=None)
Parameters
a |
Required. Specify first array-like argument. |
b |
Required. Specify second array-like argument. |
out |
Optional. Specify a location into which the result is stored. If provided, it must have the right type, must be C-contiguous, and its dtype must be the dtype that would be returned for dot(a,b). |
Return Value
Returns the dot product of a and b. If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. If out is given, then it is returned.
Exception
Raises ValueError exception, if the last dimension of a is not the same size as the second-to-last dimension of b.
Example: dot() function with scalars
The example below shows the result when two scalars are used with dot() function.
import numpy as np print(np.dot(5, 10))
The output of the above code will be:
50
Example: dot() function with 1-D arrays
When two 1-D arrays are used, the function returns inner product of the arrays.
import numpy as np Arr1 = [5, 8] Arr2 = [10, 20] #returns 5*10 + 8*20 = 210 print(np.dot(Arr1, Arr2))
The output of the above code will be:
210
Example: dot() function with complex numbers
The dot() function can be used with complex numbers. Consider the following example.
import numpy as np Arr1 = np.array([1+2j, 1+3j]) Arr2 = np.array([2+2j, 2+3j]) Arr3 = np.dot(Arr1, Arr2) print(Arr3)
The output of the above code will be:
(-9+15j)
The dot product is calculated as:
= (1+2j)*(2+2j) + (1+3j)*(2+3j) = (-2+6j) + (-7+9j) = (-9+15j)
Example: dot() function with matrix
When two matrix are used, the function returns matrix multiplication.
import numpy as np Arr1 = np.array([[1, 2], [3, 4]]) Arr2 = np.array([[10, 20], [30, 40]]) Arr3 = np.dot(Arr1, Arr2) print(Arr3)
The output of the above code will be:
[[ 70 100] [150 220]]
The dot product is calculated as:
[[1*10+2*30 1*20+2*40] [3*10+4*30 3*20+4*40]] = [[ 70 100] [150 220]]
❮ NumPy - Functions