np.mesharid()
函数通常用来生成二维数据网格,例如一张灰度图片中长为x轴,宽为y轴,图中每一个像素点。
可以接受两个一维数组生成两个二维矩阵:
np.meshgrid(np.arange(4),np.arange(4))
我们生成的结果为:
[array([[0, 1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3]]),
array([[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]])]
根据传入的两个一维数组参数生成两个数组元素的列表。
如果第一个参数是x array,维度是x dimesion,第二个参数是y array,维度是y dimesion。
那么生成的第一个二维数组是以x array为行,共y dimesion行的向量;而第二个二维数组是以y array的转置为列,共x dimesion列的向量。
直观的感受:x-y坐标系中,x可取(1,2,3) y可取(4,5)
共有6个点 (1,4)(1,5)(2,4)(2,5)(3,4)(3,5)
np.mesharid()
函数就是生成类似的数据网格。
我们看一个示例:
import numpy as np
import matplotlib.pyplot as plt
# np建立一个等差数列
x = np.arange(0,10,1)
print(f"x的维度:{x.ndim},shape:{x.shape}")
print(x)
y = np.arange(0,10,2)
print(f"y的维度:{y.ndim},shape:{y.shape}")
print(y)
xx,yy = np.meshgrid(x, y)
print(f"xv的维度:{xx.ndim},shape:{xx.shape}")
print(f"yv的维度:{yy.ndim},shape:{yy.shape}")
plt.plot(xx, yy,'.')
plt.grid(True)
plt.show()
结果为:
x的维度:1,shape:(10,)
[0 1 2 3 4 5 6 7 8 9]
y的维度:1,shape:(5,)
[0 2 4 6 8]
xv的维度:2,shape:(5, 10)
yv的维度:2,shape:(5, 10)