Element-wise multiplication with reshaped arrays using NumPy
NumPy: Broadcasting Exercise-5 with Solution
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.
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