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?
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]])
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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With