4

I have two Numpy arrays A (n x 1) and B (m x 1) of different sizes. I want to subtract each element of B from all the elements of A. Thus the elements of the result matrix C (m x n) should be computed as c(i,j) = A(i)-B(j). Is there any direct loop-less computation using Numpy?

4
  • have you looked at numpy.subtract? Commented Jul 19, 2019 at 14:39
  • 1
    Possible duplicate of Subtract values in one list from corresponding values in another list Commented Jul 19, 2019 at 14:40
  • Why can't it be a loop? Commented Jul 19, 2019 at 14:40
  • @JakeP Numpy.subtract does not help. Please note that arrays are not of the same size, and I want to subtract A from every single element of B. Commented Jul 19, 2019 at 14:46

3 Answers 3

7

Broadcasting:

A = np.array([1,2,3,4,5])
B = np.array([5,4,2,7])
A - B[:, np.newaxis]

Output:

array([[-4, -3, -2, -1,  0],
       [-3, -2, -1,  0,  1],
       [-1,  0,  1,  2,  3],
       [-6, -5, -4, -3, -2]])
Sign up to request clarification or add additional context in comments.

Comments

4

You can use np.meshgrid

A = np.array([1,2,3,4,5])
B = np.array([5,4,2,7])
a, b= np.meshgrid(A,B)
print(a - b)

#output:- 
array([[-4, -3, -2, -1,  0],
       [-3, -2, -1,  0,  1],
       [-1,  0,  1,  2,  3],
       [-6, -5, -4, -3, -2]])

Second method:-

C = A - np.array([B]).T
print(C)

#output:- 
array([[-4, -3, -2, -1,  0],
       [-3, -2, -1,  0,  1],
       [-1,  0,  1,  2,  3],
       [-6, -5, -4, -3, -2]])

Comments

-1

You can be a little more efficient than a straightforward loop if you use list comprehension:

import numpy as np

a = np.array([10, 20, 30, 40])
b = np.array([1, 2])


c = np.array([a - b[j] for j in range(len(b))])
print(c)

output:

[[ 9 19 29 39]
 [ 8 18 28 38]]

2 Comments

that's loop's use; not what OP wants.
it's still a loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.