w3resource

NumPy: Broadcast on different shapes of arrays where p(3,3) + q(3)

NumPy: Array Object Exercise-124 with Solution

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

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

Pictorial Presentation:

NumPy: Broadcast on different shapes of arrays where p(3,3) + q(3)

Sample Solution:

Python Code:

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

# Creating a NumPy array 'p' with 3x3 elements
p = np.array([[0, 0, 0],
              [1, 2, 3],
              [4, 5, 6]])

# 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'
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 0 0]
 [1 2 3]
 [4 5 6]]
Array-2
[10 11 12]

New Array:
[[10 11 12]
 [11 13 15]
 [14 16 18]]

Explanation:

In the above exercise –

‘p’ is a 3x3 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 3x3 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 3x1 array and is broadcasted across the columns of the 3x3 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’.

Python-Numpy Code Editor:

Previous: Write a NumPy program to create two arrays when the size is bigger or smaller than a given array
Next: Write a NumPy program to broadcast on different shapes of arrays where a(,3) + b(3).

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.