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)?
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. ]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With