w3resource

Compute Outer Subtraction of Two 1D Arrays Using np.subtract.outer

NumPy: Universal Functions Exercise-11 with Solution

ufunc Outer Method:

Write a NumPy program that uses the np.subtract.outer ufunc to compute the outer subtraction of two 1D arrays.

Sample Solution:

Python Code:

import numpy as np

# Create two 1D NumPy arrays
array_1 = np.array([1, 2, 3])
array_2 = np.array([4, 5, 6])

# Use the np.subtract.outer ufunc to compute the outer subtraction
outer_subtraction = np.subtract.outer(array_1, array_2)

# Print the original arrays and the resulting outer subtraction array
print('Array 1:', array_1)
print('Array 2:', array_2)
print('Outer subtraction of Array 1 and Array 2:\n', outer_subtraction)

Output:

Array 1: [1 2 3]
Array 2: [4 5 6]
Outer subtraction of Array 1 and Array 2:
 [[-3 -4 -5]
 [-2 -3 -4]
 [-1 -2 -3]]

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
  • Create Two 1D NumPy Arrays:
    • Created two 1D NumPy arrays named array_1 with values [1, 2, 3] and array_2 with values [4, 5, 6].
  • Compute Outer Subtraction with np.subtract.outer:
    • Used the np.subtract.outer "ufunc" to compute the outer subtraction of the two 1D arrays. This computes the subtraction of each element in 'array_1' with each element in 'array_2', resulting in a 2D array.
  • Finally print the original arrays and the resulting outer subtraction array to verify the operation.

Python-Numpy Code Editor:

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

Previous: Compute cumulative product of elements using np.multiply.accumulate.
Next: Compute Dot Product using np.dot and custom ufunc in NumPy.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/compute-outer-subtraction-of-two-1d-arrays-using-np-dot-subtract-dot-outer.php