Siraj S.
Siraj S.

Reputation: 3751

subtract every element of 1D numpy array with every other element of the same array

consider the below array

np.array([a,b,c]) #where a,b and c are some integers

i with to do something like this

[(a-b),(a-c),(b-c)] #basically subtract each element in the array with every other element except for itself

this is somewhat like a matrix but there is no need to do something like (a-a) or repeat instance which are basically just the reverse like (b - a) or (c - b) is reverse of (a - b) and (a - c)

If this were a product there are some ready to use functions available like np.kron but how to handle non-product operations like this?

the closest i have got to is:

(a[0] - np.choose([1,2],a))

this basically give me (a-b) and (a - c) but still (b - c) remains. Any suggestions?

Upvotes: 1

Views: 1385

Answers (1)

Divakar
Divakar

Reputation: 221514

Get those pair-wise indices withtriu_indices/tril_indices and then simply index and subtract. Thus, the implementation would be -

r,c = np.triu_indices(a.size,1) # Input array : a
out = a[r] - a[c]

Sample run -

In [159]: a = np.array([3,5,6])

In [160]: r,c = np.triu_indices(a.size,1)

In [161]: a[r] - a[c]
Out[161]: array([-2, -3, -1])

In [162]: a[0] - a[1]
Out[162]: -2

In [163]: a[0] - a[2]
Out[163]: -3

In [164]: a[1] - a[2]
Out[164]: -1

Upvotes: 4

Related Questions