Dec 15, 2013

From 2 Numpy vectors(length=m,n) , create crossed matrix(shape=(m, n,2))

As a reminder for MYSELF,

To create a matrix from two 1D vectors, like

v1 = np.arange(4)           #[0,1,2,3]
v2 = np.arange(4) *10    #[0,10,20,30]

to create crossed matrix

[[[0,0],[0,10],[0,20],[0,30]],
  [[1,0],[1,10],[1,20],[1,30]],
  [[2,0],[2,10],[2,20],[2,30]],
  [[3,0],[3,10],[3,20],[3,30]]]
I do
crossed = np.dstack(( np.zeros((len(v1),len(v2)), dtype=v1.dtype) + v1[...,np.newaxis], 
                                    np.zeros((len(v1),len(v2)),dtype=v2.dtype) + v2))
Is there any better way to do it? Any suggestion will be appreciated.

No comments: