Add two vectors using broadcasting in Numpy



To produce an object that mimics broadcasting, use the numpy.broadcast() method in Python Numpy. A set of arrays is said to be broadcastable if the above rules produce a valid result and one of the following is true −

  • Arrays have exactly the same shape.
  • Arrays have the same number of dimensions and the length of each dimension is either a common length or 1.
  • Array having too few dimensions can have its shape prepended with a dimension of length 1, so that the above stated property is true.

Steps

At first, import the required library −

import numpy as np

Create two arrays −

arr1 = np.array([[5, 10, 15], [25, 30, 35]])
arr2 = np.array([[7, 14, 21], [28, 35, 56]])

Display the arrays −

print("Array 1...
", arr1) print("
Array 2...
", arr2)

Get the type of the arrays −

print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype)

Get the dimensions of the Arrays −

print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim)

Get the shape of the Arrays −

print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape)

To produce an object that mimics broadcasting, use the numpy.broadcast () method −

x = np.broadcast(arr1, arr2)
res = np.empty(x.shape)
res.flat = [i+j for (i,j) in x]
print("
Result...
",res)

Example

import numpy as np

# Create two arrays
arr1 = np.array([[5, 10, 15], [25, 30, 35]])
arr2 = np.array([[7, 14, 21], [28, 35, 56]])

# Display the arrays
print("Array 1...
", arr1) print("
Array 2...
", arr2) # Get the type of the arrays print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype) # Get the dimensions of the Arrays print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim) # Get the shape of the Arrays print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape) # To produce an object that mimics broadcasting, use the numpy.add() method in Python Numpy x = np.broadcast(arr1, arr2) res = np.empty(x.shape) res.flat = [i+j for (i,j) in x] print("
Result...
",res)

Output

Array 1...
[[ 5 10 15]
[25 30 35]]

Array 2...
[[ 7 14 21]
[28 35 56]]

Our Array 1 type...
int64

Our Array 2 type...
int64

Our Array 1 Dimensions...
2

Our Array 2 Dimensions...
2

Our Array 1 Shape...
(2, 3)

Our Array 2 Shape...
(2, 3)

Result...
[[12. 24. 36.]
[53. 65. 91.]]

Advertisements