Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract each element of an array from another array?

Tags:

python

numpy

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?

like image 508
Saeed Reza Kheradpisheh Avatar asked Oct 21 '25 12:10

Saeed Reza Kheradpisheh


2 Answers

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]])
like image 177
Mark Bakker Avatar answered Oct 24 '25 01:10

Mark Bakker


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]])
like image 30
Vicrobot Avatar answered Oct 24 '25 03:10

Vicrobot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!