w3resource

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

NumPy: Array Object Exercise-186 with Solution

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.

Python-Numpy Code Editor:

Previous:Write a NumPy program to create a new vector with 2 consecutive 0 between two values of a given vector.
Next: Write a NumPy program to convert a given vector of integers to a matrix of binary representation.

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.