บทนำ
numpy.meshgrid() ใช้สำหรับสร้างเมทริกซ์พิกัดจากเวกเตอร์พิกัด ไวยากรณ์คือดังนี้:
numpy.meshgrid(*xi, **kwargs)
พารามิเตอร์
- x1, x2, ..., xn – พิกัดของกริด
- indexing – พารามิเตอร์ทางเลือก กำหนดดัชนีแบบการ์ทีเซียน 'xy' (ค่าเริ่มต้น) หรือแบบเมทริกซ์ 'ij'
- sparse – พารามิเตอร์ทางเลือก หากต้องการใช้กริดแบบกระจัดกระจาย (sparse grid) เพื่อประหยัดหน่วยความจำ ตั้งค่าเป็น True (ค่าเริ่มต้น: False)
- copy – คืนค่าสำเนาของอาเรย์ต้นฉบับเพื่อประหยัดหน่วยความจำเมื่อเป็น True (ค่าเริ่มต้น: False)
ตัวอย่างที่ 1: การใช้ sparse=True
import numpy as np
# อาเรย์อินพุต
x = np.array([1, 2, 3, 4, 5])
y = np.array([11, 12, 13, 14, 15])
print("Input x :\n", x)
print("Input y :\n", y)
# meshgrid() ด้วย sparse=True
xx, yy = np.meshgrid(x, y, sparse=True)
print("Meshgrid of X:", xx)
print("Meshgrid of Y:\n", yy)
ผลลัพธ์
Input x : [1 2 3 4 5]
Input y : [11 12 13 14 15]
Meshgrid of X: [[1 2 3 4 5]]
Meshgrid of Y: [[11]
[12]
[13]
[14]
[15]]
ตัวอย่างที่ 2: เปรียบเทียบ linspace และ meshgrid
import numpy as np
# linspace function
a = np.linspace(3, 4, 4)
b = np.linspace(4, 5, 6)
print("linspace of a :", a)
print("linspace of b :", b)
# meshgrid function
xa, xb = np.meshgrid(a, b)
print("Meshgrid of xa :\n", xa)
print("Meshgrid of xb :\n", xb)
ผลลัพธ์
linspace of a : [3. 3.33333333 3.66666667 4.] linspace of b : [4. 4.2 4.4 4.6 4.8 5.] Meshgrid of xa : [[3. 3.33333333 3.66666667 4.] [3. 3.33333333 3.66666667 4.] [3. 3.33333333 3.66666667 4.] [3. 3.33333333 3.66666667 4.] [3. 3.33333333 3.66666667 4.] [3. 3.33333333 3.66666667 4.]] Meshgrid of xb : [[4. 4. 4. 4.] [4.2 4.2 4.2 4.2] [4.4 4.4 4.4 4.4] [4.6 4.6 4.6 4.6] [4.8 4.8 4.8 4.8] [5. 5. 5. 5.]]