1. 程式人生 > >np.mgird np.ogrid

np.mgird np.ogrid

np.ogrid:  

address:https://docs.scipy.org/doc/numpy/reference/generated/numpy.ogrid.html

returns an open (i.e. not fleshed out) mesh-grid when indexed, only one dimension of each returned array is greater than 1.

The dimension and number of the output arrays are equal to the number of indexing dimensions.

If the step length is not a complex number, then the stop is not inclusive.

if the step length is a complex number (e.g. 5j), then the integer part of its magnitude is interpreted as specifying the number of points to create between the start and stop values, where the stop value is inclusive.

上面幾條翻譯過來就是:

返回陣列的維度只有一個大於1.

返回陣列的個數和維度等於輸入時索引維度的個數.

若步長不是複數,就不包含stop.

若步長是複數,其整數部分表示在start和stop之間建立的點數(start和stop也算),包含stop.

 

下面示例解釋前2條:

 1 a, b, c = np.ogrid[0:2, 0:2, 0:2]
 2 print(a.shape, b.shape, c.shape)
 3 print(a)
 4 print(b)
 5 print(c)
 6 
 7 a, b, c, d = np.ogrid[0:2, 0:2, 0:2, 0:2]
 8 print
(a.shape, b.shape, c.shape, d.shape) 9 10 result: 11 (2, 1, 1) (1, 2, 1) (1, 1, 2) 12 [[[0]] 13 14 [[1]]] 15 [[[0] 16 [1]]] 17 [[[0 1]]] 18 (2, 1, 1, 1) (1, 2, 1, 1) (1, 1, 2, 1) (1, 1, 1, 2)

解釋第3條:

 1 a, b, c = np.ogrid[0:4:2, 0:5:3, 0:5:1]
 2 print(a.shape, b.shape, c.shape)
 3 print(a)
 4 print(b)
 5 print(c)
 6 
 7 result:
 8 (2, 1, 1) (1, 2, 1) (1, 1, 5)
 9 [[[0]]
10 
11  [[2]]]  # 不包含stop
12 [[[0]
13   [3]]]
14 [[[0 1 2 3 4]]]  # 不包含stop

解釋第4條:

 1 a, b, c = np.ogrid[0:4:3j, 0:5:3j, 0:5:4j]
 2 print(a.shape, b.shape, c.shape)
 3 print(a)
 4 print(b)
 5 print(c)
 6 
 7 result:
 8 (3, 1, 1) (1, 3, 1) (1, 1, 4)
 9 [[[0.]]
10 
11  [[2.]]
12 
13  [[4.]]]  # 包含stop
14 [[[0. ]
15   [2.5]
16   [5. ]]]
17 [[[0.         1.66666667 3.33333333 5.        ]]]  # 包含stop

 

np.mgrid: 

address: https://docs.scipy.org/doc/numpy/reference/generated/numpy.mgrid.html

除第1條不同外,其他3條完全一樣:

returns an dense (or fleshed out) mesh-grid when indexed, each returned argument has the same shape.

 1 N = 100
 2 X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
 3 print(X.shape, Y.shape)  # (100, 100) (100, 100)
 4 # X是每行都相等,每列遞增;Y是每行都相等,每列遞增
 5 print(X)
 6 # [[-3.         -3.         -3.         ... -3.         -3.
 7 #   -3.        ]
 8 #  [-2.93939394 -2.93939394 -2.93939394 ... -2.93939394 -2.93939394
 9 #   -2.93939394]
10 #  [-2.87878788 -2.87878788 -2.87878788 ... -2.87878788 -2.87878788
11 #   -2.87878788]
12 #  ...
13 #  [ 2.87878788  2.87878788  2.87878788 ...  2.87878788  2.87878788
14 #    2.87878788]
15 #  [ 2.93939394  2.93939394  2.93939394 ...  2.93939394  2.93939394
16 #    2.93939394]
17 #  [ 3.          3.          3.         ...  3.          3.
18 #    3.        ]]
19 print(Y)
20 # [[-2.         -1.95959596 -1.91919192 ...  1.91919192  1.95959596
21 #    2.        ]
22 #  ...
23 #  [-2.         -1.95959596 -1.91919192 ...  1.91919192  1.95959596
24 #    2.        ]]