Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 991
Cupitor Avatar asked Nov 15 '13 18:11

Cupitor


1 Answers

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.        ]])
like image 118
Jaime Avatar answered Nov 15 '22 15:11

Jaime