This question already has answers here:
Cartesian product of x and y array points into single array of 2D points
(12个答案)
5年前关闭。
假设我有两个向量:
A=linspace(-2,0,6)
B=linspace(0,2,6)

我想创建一个二维矩阵(大小为2×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. ]])

07-27 19:50