Reputation: 11067
I start with an array of shape (n,d) containing n particle-vectors of length d dimensions, and want to construct an array containing the inter-particle vectors, of shape (n,n,d) which I'll go on to use for calculating forces etc in a Newtonian simulation.
I want to be able to generalise this for any number of dimensions, so the position vectors could be of any d, and have come up with the below, building the new dimension one array at a time into a list that I then convert back into an array. But this seems clunky, and, since it must be such a common operation, I can't help thinking there's some inbuilt numpy magic that will perform this operation more quickly.
def delta_matrix(pos_vec):
build=[]
for i in pos_vec:
build.append(i-pos_vec)
return np.array(build)
In particular then, is there a numpy method that performs this iterative type of operation?
Upvotes: 0
Views: 77
Reputation: 28437
What about list comprehension? That seems simple yet powerful enough.
def delta_matrix(pos_vec):
return np.array([i-pos_vec for i in pos_vec])
Upvotes: 2