Search code examples
pythonnumpylist-comprehensionarray-broadcasting

Is there a Numpy array broadcasting expression simpler than this list comprehension?


In this code snippet:

triangles = np.float32([[[0, -2], [-2, 3], [1, 1]], [[0, -1], [-1, 3], [1, 1]]])
centers = np.average(triangles, axis=1)
samples = np.float32([t-centers[i] for i, t in enumerate(triangles)])

I would like to express samples as an array broadcast subtraction, i.e. something similar to triangles-centers, which doesn't work due to:

ValueError: operands could not be broadcast together with shapes (2,3,2) (2,2) 

Is there a simpler way to define samples than a list comprehension?


Solution

  • I believe this does what you want. Just reshape the centers to match the row size.

    samples = triangles - centers.reshape(triangles.shape[0],-1,triangles.shape[2])