numpy模块中的meshgrid函数用来生成网格矩阵,最简单的网格矩阵为二维矩阵
meshgrid函数可以接受 x1, x2,..., xn 等 n 个一维向量,生成 N-D 矩阵。
1 基本语法
meshgrid(*xi, **kwargs)
参数:
xi - x1, x2,..., xn : array_like
返回值:
X1, X2,..., XN : ndarray
2 示例(二维网格)
2.1 一个参数时
import numpy as np a = [1,2,3] b = np.meshgrid(a) print(b) # [array([1, 2, 3])]
当只有一个参数时,返回值也只有一个 b ,若写两个返回值 b, c = np.meshgrid(a) 则会报错。
2.2 两个参数时
2.2.1 两个参数长度一致时
示例1
import numpy as np a = [1,2,3] b = [9,8,7] c, d = np.meshgrid(a,b) print(c) print('-'*10) print(d)
运行
[[1 2 3]
[1 2 3]
[1 2 3]]
----------
[[9 9 9]
[8 8 8]
[7 7 7]]
当两个参数长度一致时(如长度为 N ),则生成 N * N 维矩阵
示例2
交换两参数的顺序
import numpy as np a = [1,2,3] b = [9,8,7] c, d = np.meshgrid(b,a) print(c) # [[9 8 7] # [9 8 7] # [9 8 7]] print(d) # [[1 1 1] # [2 2 2] # [3 3 3]]
交换两个参数顺序后,输出结果发生了变化。
示例3
当返回值值是两个或两个以上参数时,也可用一个参数来接受。
import numpy as np a = [1,2,3] b = [9,8,7] c = np.meshgrid(a,b) print(c) # 下面是打印出的结果+ # [array([[1, 2, 3], # [1, 2, 3], # [1, 2, 3]]), array([[9, 9, 9], # [8, 8, 8], # [7, 7, 7]])]
2.2.2 两个参数长度不一致时
import numpy as np a = [1,2,3] b = [9,8] c, d = np.meshgrid(a,b) print(c) # [[1 2 3] # [1 2 3]] print(d) # [[9 9 9] # [8 8 8]]
这是一个 2 * 3(2 行 3 列)
相当于 b 由 行向量 变成了 列向量。
import numpy as np a = [1,2,3] b = [9,8] c, d = np.meshgrid(b, a) print(c) # [[9 8] # [9 8] # [9 8]] print(d) # [[1 1] # [2 2] # [3 3]]
3 示例(三维网格)
import numpy as np a = [1,2,3] b = [4,5,6] c = [7,8,9] x, y, z = np.meshgrid(a, b, c) print(x) # [[[1 1 1] # [2 2 2] # [3 3 3]] # # [[1 1 1] # [2 2 2] # [3 3 3]] # # [[1 1 1] # [2 2 2] # [3 3 3]]] print(y) # [[[4 4 4] # [4 4 4] # [4 4 4]] # # [[5 5 5] # [5 5 5] # [5 5 5]] # # [[6 6 6] # [6 6 6] # [6 6 6]]] print(z) # [[[7 8 9] # [7 8 9] # [7 8 9]] # # [[7 8 9] # [7 8 9] # [7 8 9]] # # [[7 8 9] # [7 8 9] # [7 8 9]]]