Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การจัดการเมทริกซ์ (Matrix Manipulation) ใน Python ด้วย NumPy

ใน Python สามารถแก้ปัญหาการดำเนินการเมทริกซ์ต่างๆ ได้ โมดูล NumPy มีเมธอดต่างๆ สำหรับการดำเนินการเมทริกซ์

เมธอดหลักของ NumPy สำหรับเมทริกซ์

เมธอดคำอธิบาย
add()บวกสมาชิกของสองเมทริกซ์ (element-wise)
subtract()ลบสมาชิกของสองเมทริกซ์ (element-wise)
divide()หารสมาชิกของสองเมทริกซ์ (element-wise)
multiply()คูณสมาชิกของสองเมทริกซ์ (element-wise)
dot()คูณเมทริกซ์ (matrix multiplication) ไม่ใช่ element-wise
sqrt()รากที่สองของแต่ละสมาชิกในเมทริกซ์
sum(x, axis)ผลรวมสมาชิกทั้งหมด axis=0: ผลรวมคอลัมน์, axis=1: ผลรวมแถว
.Tทรานส์โพส (Transpose) เมทริกซ์

โค้ดตัวอย่างครบถ้วน


import numpy as np

# สร้างเมทริกซ์ 2x2
x = np.array([[1, 2], [4, 5]])
y = np.array([[7, 8], [9, 10]])

print("Matrix X:")
print(x)
print("\nMatrix Y:")
print(y)

# การดำเนินการ Element-wise
print("\nAddition (element-wise):")
print(np.add(x, y))

print("\nSubtraction (element-wise):")
print(np.subtract(x, y))

print("\nDivision (element-wise):")
print(np.divide(x, y))

print("\nMultiplication (element-wise):")
print(np.multiply(x, y))

# Matrix Multiplication (Dot Product)
print("\nMatrix Multiplication (dot product):")
print(np.dot(x, y))

# Square root
print("\nSquare root of X:")
print(np.sqrt(x))

# Summation
print("\nSum of all elements in Y:", np.sum(y))
print("Column-wise sum (axis=0):", np.sum(y, axis=0))
print("Row-wise sum (axis=1):", np.sum(y, axis=1))

# Transpose
print("\nTranspose of X:")
print(x.T)

ผลลัพธ์

Matrix X:
[[1 2]
 [4 5]]

Matrix Y:
[[ 7  8]
 [ 9 10]]

Addition (element-wise):
[[ 8 10]
 [13 15]]

Subtraction (element-wise):
[[-6 -6]
 [-5 -5]]

Division (element-wise):
[[0.14285714 0.25      ]
 [0.44444444 0.5       ]]

Multiplication (element-wise):
[[ 7 16]
 [36 50]]

Matrix Multiplication (dot product):
[[25 28]
 [73 82]]

Square root of X:
[[1.         1.41421356]
 [2.         2.23606798]]

Sum of all elements in Y: 34
Column-wise sum (axis=0): [16 18]
Row-wise sum (axis=1): [15 19]

Transpose of X:
[[1 4]
 [2 5]]

ข้อสังเกตสำคัญ

  • multiply() = element-wise multiplication (Hadamard product)
  • dot() = matrix multiplication ตามกฎคณิตศาสตร์ (rows × columns)
  • เมทริกซ์ต้องมีขนาดเข้ากันสำหรับ element-wise operations
  • สำหรับ dot() จำนวนคอลัมน์ของเมทริกซ์แรก ต้องเท่าจำนวนแถวของเมทริกซ์ที่สอง