w3resource

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


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: