Reputation: 1814
I want to create a line between two points in 3d space:
origin = np.array((0,0,0),'d')
final = np.array((1,2,3),'d')
delta = final-origin
npts = 25
points np.array([origin + i*delta for i in linspace(0,1,npts)])
But this is silly: I build a big python list and then pass it into numpy, when I'm sure there's a way to do this with numpy alone. How do the numpy wizards do something like this?
Upvotes: 3
Views: 137
Reputation: 879899
Perhaps use np.column_stack:
In [71]: %timeit np.column_stack((np.linspace(o,f,npts) for o,f in zip(origin,final)))
10000 loops, best of 3: 45 us per loop
In [77]: %timeit np.array([origin + i*delta for i in np.linspace(0,1,npts)])
10000 loops, best of 3: 138 us per loop
Note: Jaime's answer is faster:
In [92]: %timeit origin + (final-origin)*np.linspace(0, 1, npts)[:, np.newaxis]
10000 loops, best of 3: 21.1 us per loop
Upvotes: 1
Reputation: 67437
You can do away with all Python loops for this one with a little broadcasting:
origin + delta*np.linspace(0, 1, npts)[:, np.newaxis]
Upvotes: 3