w3resource

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

NumPy: Array Object Exercise-146 with Solution

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’.

Python-Numpy Code Editor:

Previous: Write a NumPy program to extract first, third and fifth elements of the third and fifth rows from a given (6x6) array.
Next: Write a NumPy program to create an array that represents the rank of each item of a given array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/python-numpy-exercise-146.php