5

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!

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

6 Comments

Here's a more concise version: diffs = arr[:, None] - arr[None, :]. This is an example of numpy's broadcasting capability (docs.scipy.org/doc/numpy/user/basics.broadcasting.html).
I'm exploiting broadcasting already; what you did there was to use newaxis implicitly (which is a nice solution). I'll add it to the answer, thanks!
Sorry, I didn't mean to imply that you weren't using broadcasting! That statement was meant as a general comment about the method.
Thank you both Warren and Nneoneo...could you give any tips on how to no sum the results but not over the whole array, rather only summing the results row by row?
In other words...the above results in an 3X3 array...is there a way I could sum up each entry individually? [0][0] [0][1] [0][2]....
|
0

Check out scipy.spatial.distance, you have functions for all vs all distances.

1 Comment

I was looking to stay within the numpy library. Any tips?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.