3

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
Community
  • 1
  • 1
Hooked
  • 84,485
  • 43
  • 192
  • 261

2 Answers2

9

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

JoshAdel
  • 66,734
  • 27
  • 141
  • 140
8

Try

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

instead. Broadcasting will automatically do The Right Thing.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • So the mistake was trying to shoehorn the `CM` array into the subtraction instead of solving it in one shot? – Hooked Jan 18 '12 at 21:16
  • @Hooked: You could just as well do `CM = R.sum(0) / len(R); R -= CM`, but I figured the intermediate variable doesn't really help readability. – Sven Marnach Jan 18 '12 at 21:24