w3resource

NumPy: Multiply an array of dimension by an array with dimensions


Multiply arrays of compatible dimensions.

Write a NumPy program to multiply an array of dimension (2,2,3) by an array with dimensions (2,2).

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating a NumPy array 'nums1' consisting of ones with shape (2, 2, 3)
nums1 = np.ones((2, 2, 3))

# Creating another NumPy array 'nums2' consisting of threes with shape (2, 2)
nums2 = 3 * np.ones((2, 2))

# Displaying the original array 'nums1'
print("Original array:")
print(nums1)

# Performing element-wise multiplication of 'nums1' and 'nums2' along the second axis using None to add a new axis
new_array = nums1 * nums2[:, :, None]

# Displaying the new array obtained after the multiplication
print("\nNew array:")
print(new_array)

Sample Output:

Original array:
[[[1. 1. 1.]
  [1. 1. 1.]]

 [[1. 1. 1.]
  [1. 1. 1.]]]

New array:
[[[3. 3. 3.]
  [3. 3. 3.]]

 [[3. 3. 3.]
  [3. 3. 3.]]]

Explanation:

nums1 = np.ones((2,2,3)): Creates a 3D NumPy array nums1 of shape (2, 2, 3) filled with ones.

nums2 = 3*np.ones((2,2)): Creates a 2D NumPy array nums2 of shape (2, 2) filled with threes.

new_array = nums1 * nums2[:,:,None]

In the above code -

  • nums2[:,:,None]: Adds a new axis to nums2 to make it a 3D array with shape (2, 2, 1). This is done to match the shape of nums1 for broadcasting.
  • new_array = nums1 * nums2[:,:,None]: Performs element-wise multiplication of nums1 and the reshaped nums2, using broadcasting. Since nums1 contains ones and nums2 contains threes, the resulting new_array will be a 3D array of shape (2, 2, 3) filled with threes.

For more Practice: Solve these Related Problems:

  • Write a NumPy program to multiply a 3D array of shape (2,2,3) with a 2D array of shape (2,2) using broadcasting.
  • Create a function that scales each 2D sub-array by corresponding elements of a smaller array.
  • Implement a solution that reshapes the 2D array to allow element-wise multiplication with the 3D array.
  • Test the multiplication on arrays with random values to ensure that broadcasting rules are correctly applied.

Go to:


PREV : Insert zeros between elements in an array.
NEXT : Convert integer vector to binary matrix.


Python-Numpy Code Editor:

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

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.