w3resource

NumPy: Broadcast on different shapes of arrays where a(,3) + b(3)

NumPy: Array Object Exercise-125 with Solution

Write a NumPy program to broadcast on different shapes of arrays where a(,3) + b(3).

The a variable has a shape of (, 3), while b only has a shape of 3.

Pictorial Presentation:

NumPy: Broadcast on different shapes of arrays where a(,3) + b(3)

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array 'p' with 3x1 elements
p = np.array([[0], [10], [20]])

# Creating another NumPy array 'q' with 1x3 elements
q = np.array([10, 11, 12])

# Printing a message indicating the original arrays will be displayed
print("Original arrays:")
print("Array-1")  # Printing the message for Array-1
print(p)         # Displaying Array-1
print("Array-2")  # Printing the message for Array-2
print(q)         # Displaying Array-2

# Printing a message indicating the creation of a new array by adding Array-1 and Array-2
print("\nNew Array:")

# Adding Array-1 'p' and Array-2 'q' element-wise to create a new array 'new_array1'
# NumPy performs broadcasting here to match the shapes for addition
new_array1 = p + q

# Displaying the new array obtained by adding Array-1 and Array-2
print(new_array1) 

Sample Output:

Original arrays:
Array-1
[[ 0]
 [10]
 [20]]
Array-2
[10 11 12]

New Array:
[[10 11 12]
 [20 21 22]
 [30 31 32]]

Explanation:

In the above exercise -

‘p’ is a 3x1 2D array and ‘q’ is a 1D array with three elements: [10, 11, 12].

new_array1 = p + q: In this line NumPy performs element-wise addition between the 3x1 array p and the 1D array q. Broadcasting rules apply in this case, as the shapes of the arrays are different. The 1D array q is treated as a 1x3 array and is broadcasted across the rows of the 3x1 array p. The resulting new_array1 is a 3x3 array, where each element is the sum of the corresponding elements in p and the broadcasted q.

Finally print() function print the ‘new_array1’.

Python-Numpy Code Editor:

Previous: Write a NumPy program to broadcast on different shapes of arrays where p(3,3) + q(3).
Next:Write a NumPy program to rearrange the dimensions of a given array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.