简体   繁体   中英

Numpy 2D array Subtraction by row

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!

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] .

查看scipy.spatial.distance,你有所有距离的功能。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM