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:
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’.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics