NumPy Tutorial NumPy Statistics NumPy References

NumPy - broadcast() function



The NumPy broadcast() function produces an object that mimics broadcasting.

Syntax

numpy.broadcast(in1, in2, …)

Parameters

in1, in2, … Required. Specify the input parameters (array_like).

Return Value

Broadcast the input parameters against one another, and return an object that encapsulates the result.

Example:

In the example below, two arrays are added manually using broadcast() function.

import numpy as np

x = np.array([[1], [2], [3]])
y = np.array([4, 5, 6])

#using broadcast function to broadcast
#elements of x and y against one another 
b = np.broadcast(x, y)

#adding elements manually
out = np.empty(b.shape)
out.flat = [u+v for (u,v) in b]

#displaying results
print("Using broadcast() function:")
print(out)

#comparing against built-in broadcasting
print("\nUsing built-in broadcasting:")
print(x+y)

The output of the above code will be:

Using broadcast() function:
[[5. 6. 7.]
 [6. 7. 8.]
 [7. 8. 9.]]

Using built-in broadcasting:
[[5 6 7]
 [6 7 8]
 [7 8 9]]

❮ NumPy - Functions