Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy 2D array Subtraction by row

Tags:

python

numpy

I am struggling to vectorize the following operation. I have an array of x,y,z distances and I need to find the differences between each vector from one another.

temp_result = np.array([[0.8, 0., 1.], [0., -0.6, 1.],[0.8, 0., 1.]])

What I intend to do is subtract without using for loop iteration.

 temp_result[0] - temp_result[0]
 temp_result[0] - temp_result[1]
 temp_result[0] - temp_result[2]
 temp_result[1] - temp_result[0]
 temp_result[1] - temp_result[1]
 temp_result[1] - temp_result[2]
 temp_result[2] - temp_result[0]
 temp_result[2] - temp_result[1]
 temp_result[2] - temp_result[2]

thanks!

like image 219
Fatoons Avatar asked Nov 03 '22 14:11

Fatoons


1 Answers

Here's a nice reshape-based trick:

arr = temp_result
diffs = arr[:,None,:] - arr[None,:,:]

Then the vector difference between arr[i] and arr[j] is found in diffs[i,j].

like image 199
nneonneo Avatar answered Nov 15 '22 04:11

nneonneo