w3resource

NumPy: Compute xy, element-wise where x, y are two given arrays


Write a NumPy program to compute xy, element-wise where x, y are two given arrays.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating two arrays x and y
x = np.array([[1, 2], [3, 4]])
y = np.array([[1, 2], [1, 2]])

# Displaying the first array x
print("Array1: ")
print(x)

# Displaying the second array y
print("Array1: ")
print(y)

# Calculating the power of elements in array x raised to the power of elements in array y
r1 = np.power(x, y)

# Displaying the result of x raised to the power of y
print("Result- x^y:")
print(r1) 

Sample Output:

Array1: 
[[1 2]
 [3 4]]
Array1: 
[[1 2]
 [1 2]]
Result- x^y:
[[ 1  4]
 [ 3 16]]

Explanation:

In the above exercise –

x = np.array([[1, 2], [3, 4]]): This line initializes a two-dimensional NumPy array x with dimensions 2x2.

y = np.array([[1, 2], [1, 2]]): This line initializes a two-dimensional NumPy array y with dimensions 2x2.

r1 = np.power(x, y): Here, r1 will be a 2D NumPy array of the same shape as x and y, where each element of r1 is the corresponding element of x raised to the power of the corresponding element of y.

Python-Numpy Code Editor: