w3resource

NumPy: Add two arrays A and B of sizes (3,3) and (,3)


Add Arrays A (3,3) and B (,3)

Write a NumPy program to add two arrays A and B of sizes (3,3) and (,3).

Pictorial Presentation:

NumPy: Add two arrays A and B of sizes (3,3) and (,3)

Sample Solution:

Python Code:

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

# Creating a 3x3 array filled with ones
A = np.ones((3, 3))

# Creating a 1-dimensional array containing values from 0 to 2
B = np.arange(3)

# Displaying a message indicating the original arrays will be printed
print("Original array:")
print("Array-1")

# Printing the 3x3 array 'A'
print(A)

print("Array-2")

# Printing the 1-dimensional array 'B'
print(B)

# Displaying a message indicating the addition operation will be performed between arrays 'A' and 'B'
print("A + B:")

# Performing element-wise addition between array 'A' (3x3) and array 'B' (1x3) and storing the result in 'new_array'
new_array = A + B

# Printing the resulting array obtained by adding 'A' and 'B'
print(new_array) 

Sample Output:

Original array:
Array-1
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
Array-2
[0 1 2]
A + B:
[[1. 2. 3.]
 [1. 2. 3.]
 [1. 2. 3.]]

Explanation:

In the above exercise -

A = np.ones((3,3)): The current line creates a 2-dimensional NumPy array ‘A’ with shape (3, 3) where all the elements are equal to 1.

B = np.arange(3): The current line creates a 1-dimensional NumPy array ‘B’ with elements from 0 to 2.

new_array = A + B: This line performs an element-wise addition between arrays ‘A’ and ‘B’. Since their shapes are different, NumPy uses broadcasting to match their shapes. In this case, array B is broadcasted along the rows to match the shape of array A.

print(new_array): Finally print() function prints the ‘new_array’.


For more Practice: Solve these Related Problems:

  • Write a NumPy program to add a (3,3) array to a (3,) vector using broadcasting and verify the element-wise sum.
  • Create a function that takes two arrays of these shapes and returns their sum, ensuring proper broadcasting.
  • Test the addition operation on arrays with different constant values and verify the result matches expectations.
  • Implement a solution that demonstrates the broadcasting rules by explicitly reshaping the vector before addition.

Go to:


PREV : Extract First, Third, Fifth Elements of Third/Fifth Rows of 6x6 Array
NEXT : Rank Items in Array


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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.