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:

import numpy as np
nums1 = np.ones((2,2,3))
nums2 = 3*np.ones((2,2))
print("Original array:")
print(nums1)
new_array = nums1 * nums2[:,:,None]
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.]]]

Python Code Editor:

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

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 Python skills with w3resource's quiz



Python: Tips of the Day

List comprehension:

>>> m = [x ** 2 for x in range(5)]
>>> m
[0, 1, 4, 9, 16]