NumPy BroadcastingIn 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. ExampleOutput: [ 2 8 18 32 50 72 98] However, in the above example, if we consider arrays of different shapes, we will get the errors as shown below. ExampleOutput: ValueError: operands could not be broadcast together with shapes (7,) (8,) 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 RulesBroadcasting 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. ExampleOutput: printing array a.. [[ 1 2 3 4] [ 2 4 5 6] [10 20 39 3]] printing array b.. [2 4 6 8] Adding arrays a and b .. [[ 3 6 9 12] [ 4 8 11 14] [12 24 45 11]]
Next TopicNumPy Array Iteration
