这个问题已经在这里有了答案: > Numpy: cartesian product of x and y array points into single array of 2D points 12个
说我有两个向量:
A=linspace(-2,0,6)
B=linspace(0,2,6)
并且我想创建一个二维矩阵(大小为2 x 36),将A中的所有值与B中的所有值进行匹配,因此它类似于:
[[-2 , 0]
[-2 , 0.4]
[-2 , 0.8]
[-2 , 1.2]
[-2 , 1.6]
[-2 , 2.0]
[-1.6 , 0]
[-1.6 , 0.4]
[-1.6 , 0.8]
....
....
[0 , 2.0]]
我想我需要某种for循环,但是我不确定如何做到这一点…
解决方法:
>>> a = np.linspace(-2, 0, 6)
>>> b = np.linspace(0, 2, 6)
>>>
>>> out = np.empty((len(a), len(b), 2))
>>> out[..., 0] = a[:, None]
>>> out[..., 1] = b[None, :]
>>> out = out.reshape(-1, 2)
>>> out
array([[-2. , 0. ],
[-2. , 0.4],
[-2. , 0.8],
[-2. , 1.2],
[-2. , 1.6],
[-2. , 2. ],
[-1.6, 0. ],
[-1.6, 0.4],
[-1.6, 0.8],
[-1.6, 1.2],
[-1.6, 1.6],
[-1.6, 2. ],
[-1.2, 0. ],
[-1.2, 0.4],
[-1.2, 0.8],
[-1.2, 1.2],
[-1.2, 1.6],
[-1.2, 2. ],
[-0.8, 0. ],
[-0.8, 0.4],
[-0.8, 0.8],
[-0.8, 1.2],
[-0.8, 1.6],
[-0.8, 2. ],
[-0.4, 0. ],
[-0.4, 0.4],
[-0.4, 0.8],
[-0.4, 1.2],
[-0.4, 1.6],
[-0.4, 2. ],
[ 0. , 0. ],
[ 0. , 0.4],
[ 0. , 0.8],
[ 0. , 1.2],
[ 0. , 1.6],
[ 0. , 2. ]])