w3resource

Element-wise multiplication with reshaped arrays using NumPy


5. Reshape Arrays for Element-wise Multiplication

Given two arrays, x = np.array([1, 2, 3]) and y = np.array([4, 5, 6, 7, 8, 9]). Write a Numpy program that reshapes x and y to make them broadcast-compatible and perform element-wise multiplication.

Sample Solution:

Python Code:

# Import the NumPy library
import numpy as np

# Create a 1D array x
x = np.array([1, 2, 3])

# Create a 1D array y
y = np.array([4, 5, 6, 7, 8, 9])

# Reshape x to be a column vector (3, 1)
x_reshaped = x.reshape(3, 1)

# Reshape y to be a row vector (1, 6)
y_reshaped = y.reshape(1, 6)

# Perform element-wise multiplication using broadcasting
result = x_reshaped * y_reshaped

# Print the reshaped arrays and the result
print("Reshaped Array x:\n", x_reshaped)
print("Reshaped Array y:\n", y_reshaped)
print("Result of element-wise multiplication:\n", result)

Output:

Reshaped Array x:
 [[1]
 [2]
 [3]]
Reshaped Array y:
 [[4 5 6 7 8 9]]
Result of element-wise multiplication:
 [[ 4  5  6  7  8  9]
 [ 8 10 12 14 16 18]
 [12 15 18 21 24 27]]

Explanation:

  • Import the NumPy library: This step imports the NumPy library, which is essential for numerical operations.
  • Create a 1D array x: We create a 1D array x with elements [1, 2, 3].
  • Create a 1D array y: We create a 1D array y with elements [4, 5, 6, 7, 8, 9].
  • Reshape x to be a column vector (3, 1): We use x.reshape(3, 1) to change x into a column vector with shape (3, 1).
  • Reshape y to be a row vector (1, 6): We use y.reshape(1, 6) to change y into a row vector with shape (1, 6).
  • Perform element-wise multiplication using broadcasting: NumPy automatically broadcasts the reshaped arrays to a compatible shape and performs element-wise multiplication.
  • Print the reshaped arrays and the result: This step prints the reshaped arrays x_reshaped and y_reshaped.

For more Practice: Solve these Related Problems:

  • Reshape two 1D arrays into compatible dimensions for broadcasting, perform element-wise multiplication, and verify the resulting shape.
  • Create a function that takes two 1D arrays, reshapes one to (n, 1) and the other to (1, n), then multiplies them to form an outer product.
  • Implement a solution that uses np.reshape to align dimensions and then computes the element-wise product, followed by a sum of each row.
  • Test the function on arrays with different lengths and verify that the multiplication produces the correct 2D array.

Python-Numpy Code Editor:

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

Previous: Add Scalar to 2D array using NumPy Broadcasting.
Next: Divide columns of 2D array by 1D array using NumPy Broadcasting.

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.