Reputation: 55
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?
Upvotes: 4
Views: 8753
Reputation: 3988
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]])
Upvotes: 4
Reputation: 821
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]])
Upvotes: 7
Reputation: 389
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]]
Upvotes: -1