Hooked
Hooked

Reputation: 88148

Center of mass of a numpy array, how to make less verbose?

From what I know of numpy, it's a bad idea to apply an operation to each row of an array one at a time. Broadcasting is clearly the prefered method. Given that, how do I take data with a shape (N,3) and translate it to the center of mass? Below is the 'bad method' I'm using. This works, but I suspect it will have a performance hit for large N:

CM = R.sum(0)/R.shape[0]
for i in xrange(R.shape[0]): R[i,:] -= CM

Upvotes: 3

Views: 8356

Answers (2)

JoshAdel
JoshAdel

Reputation: 68682

As you've defined it, you can simplify your center of mass calculation as:

R -= R.mean(axis=0)

If the different elements of your array have different masses defined in mass, I would then use:

R -= np.average(R,axis=0,weights=mass)

See http://docs.scipy.org/doc/numpy/reference/generated/numpy.average.html

Upvotes: 9

Sven Marnach
Sven Marnach

Reputation: 601649

Try

R -= R.sum(0) / len(R)

instead. Broadcasting will automatically do The Right Thing.

Upvotes: 8

Related Questions