In Mathematical operations, we may need to consider the arrays of different shapes. NumPy can perform such operations where the array of different shapes are involved.
For example, if we consider the matrix multiplication operation, if the shape of the two matrices is the same then this operation will be easily performed. However, we may also need to operate if the shape is not similar.
Consider the following example to multiply two arrays.
import numpy as np a = np.array([1,2,3,4,5,6,7]) b = np.array([2,4,6,8,10,12,14]) c = a*b; print(c)
However, in the above example, if we consider arrays of different shapes, we will get the errors as shown below.
import numpy as np a = np.array([1,2,3,4,5,6,7]) b = np.array([2,4,6,8,10,12,14,19]) c = a*b; print(c)
In the above example, we can see that the shapes of the two arrays are not similar and therefore they cannot be multiplied together. NumPy can perform such operation by using the concept of broadcasting.
In broadcasting, the smaller array is broadcast to the larger array to make their shapes compatible with each other.
Broadcasting is possible if the following cases are satisfied.
Broadcasting can be applied to the arrays if the following rules are satisfied.
Let's see an example of broadcasting.
import numpy as np a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]]) b = np.array([2,4,6,8]) print("\nprinting array a..") print(a) print("\nprinting array b..") print(b) print("\nAdding arrays a and b ..") c = a + b; print(c)