Cupitor
Cupitor

Reputation: 11637

Traversing 2D line in Numpy?

I am trying to do linear combination in Numpy to get the traverse of the vector between two points, but the way I am doing is quite hideous.

import numpy as np
a=np.array([1,2])
b=np.array([3,4])
t=np.linspace(0,1,4)
c=(np.asarray([t*a[0],t*a[1]])+np.asarray([(1-t)*b[0],(1-t)*b[1]])).T
print c

Output being

[[ 3.          4.        ]
 [ 2.33333333  3.33333333]
 [ 1.66666667  2.66666667]
 [ 1.          2.        ]]

Is there any better way to do it (of course efficiently)?

Upvotes: 5

Views: 262

Answers (1)

Jaime
Jaime

Reputation: 67427

If you add a size one dimension to the end of your t array, broadcasting will take care of the details:

>>> a=np.array([1,2])
>>> b=np.array([3,4])
>>> t=np.linspace(0,1,4)
>>> t[..., None] * a  + (1 - t[..., None]) * b
array([[ 3.        ,  4.        ],
       [ 2.33333333,  3.33333333],
       [ 1.66666667,  2.66666667],
       [ 1.        ,  2.        ]])

Upvotes: 6

Related Questions