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:
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:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.