Python 使用numpy meshgrid创建矩阵
我想创建一个包含Python 使用numpy meshgrid创建矩阵,python,numpy,matrix,Python,Numpy,Matrix,我想创建一个包含M行和N列的矩阵。列中的增量始终为1,而行中的增量为常量,c。例如,要创建此矩阵,请执行以下操作: 行数为4,列数为2,行与行之间的移位:c=8。执行此操作的一种方法可以是: # Indices of columns coord_x = np.arange(0, 2) # Indices of rows coord_y = np.arange(1, 37, 9) # Creates 2 matrices with the coordinates x, y = np.mesh
M
行和N
列的矩阵。列中的增量始终为1
,而行中的增量为常量,c
。例如,要创建此矩阵,请执行以下操作:
行数为4,列数为2,行与行之间的移位:c=8
。执行此操作的一种方法可以是:
# Indices of columns
coord_x = np.arange(0, 2)
# Indices of rows
coord_y = np.arange(1, 37, 9)
# Creates 2 matrices with the coordinates
x, y = np.meshgrid(coord_x, coord_y)
# To perform the shift between columns
idx_left = x + y
输出为:
print(idx_left)
[[ 1 2]
[10 11]
[19 20]
[28 29]]
我是否可以在不添加idx_left=x+y
的情况下执行此操作?。我已经看到了其他函数,但我没有发现任何考虑沿行和列移动的函数…
为此,您可以使用np.lib.stride\u技巧
arr = np.arange(1,100)
shape = (4,2)
strides = (arr.strides[0]*9,arr.strides[0]*1) #8 bytes with 9 steps on axis=0, 8bytes with 1 step on axis=1
np.lib.stride_tricks.as_strided(arr, shape=shape, strides=strides)
另一个示例是轴上2个移位=0,轴上3个移位=1
arr = np.arange(1,100)
shape = (4,2)
strides = (arr.strides[0]*2,arr.strides[0]*3) #8bytes * 2shift on axis=0, 8bytes*3shift on axis=1
np.lib.stride_tricks.as_strided(arr, shape=shape, strides=strides)
广播
你可以简单地用同样的方法来做这件事,不需要网格,也只需要使用广播-
#Your original example
coord_x = np.arange(0, 2, 1) #start, stop, step
coord_y = np.arange(1, 37, 9)
coord_x[None,:] + coord_y[:,None]
邻域
如果有极端的限制,可以使用linspace。因此,在本例中,您可以创建一个从(1,2)到(28,29)的4行数组
经理
出于您的目的,Mgrid比网格更方便。你能行-
np.mgrid[0:2:1, 1:37:9].sum(0).T
不清楚你想要什么。您是否正在寻找使用网格网格的方法?或者您正在探索一种只沿axisHi@AkshaySehgal增加数组的方法吗?我正在寻找一种方法,以x轴和y轴为增量创建矩阵。目前,我发现最简单的方法是使用meshgrid
,最后一步是添加两个轴。我在我的答案中更新了多种方法。请检查并让我知道这是否解决了您的问题。meshgrid
使用稀疏True生成x,y
与答案的广播
示例类似。从计算上看,这些备选方案没有太大区别。谢谢!所有提供的解决方案都非常有效,但我认为linspace是更好的方法(在我的例子中,我有非常大的矩阵…)
#Your original example
coord_x = np.arange(0, 2, 1) #start, stop, step
coord_y = np.arange(1, 37, 9)
coord_x[None,:] + coord_y[:,None]
array([[ 1, 2],
[10, 11],
[19, 20],
[28, 29]])
np.linspace((1,2),(28,29),4)
array([[ 1., 2.],
[10., 11.],
[19., 20.],
[28., 29.]])
np.mgrid[0:2:1, 1:37:9].sum(0).T
array([[ 1, 2],
[10, 11],
[19, 20],
[28, 29]])