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

Matrix ใน Python อธิบายพร้อมตัวอย่าง

Matrix ใน Python คืออะไร?

Matrix ใน Python คือ Two-dimensional Array (Array 2 มิติ) ที่มีจำนวน Rows และ Columns เฉพาะ ข้อมูลใน Matrix อาจเป็นตัวเลข String หรือ Symbols ก็ได้

Matrix หรือ Two-dimensional List เป็น Data Structure สำคัญ Operations ต่างๆ เช่น Transpose, Addition, Multiplication ของ Matrix สองตัว

การประกาศ Matrix เป็น Nested List

Matrix ใน Python สร้างได้จาก Nested List โดยระบุ Rows และ Columns

# Rows=3, Cols=4
Matrix = [[0] * 4 for i in range(3)]
# [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Input Matrix Elements และ Print แบบ Row-wise

col = 4
rows = 3
matrix = [[0] * col for i in range(rows)]

for i in range(rows):
    print("Enter", "row", i+1, "elements")
    for j in range(col):
        matrix[i][j] = int(input())

def rowvise(matrix):
    for i in range(rows):
        print(matrix[i])

print("print as nested list")
print(matrix)
print("print each row in separate line")
rowvise(matrix)

ตัวอย่าง Input/Output

Enter row 1 elements
1 2 3 4
Enter row 2 elements
5 6 7 8
Enter row 3 elements
1 2 3 4
print as nested list
[[1, 2, 3, 4], [5, 6, 7, 8], [1, 2, 3, 4]]
print each row in separate line
[1, 2, 3, 4]
[5, 6, 7, 8]
[1, 2, 3, 4]

Operations พื้นฐานกับ Matrix

1. Transpose (สลับ Row/Col)

def transpose(matrix):
    return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]

# หรือใช้ zip
def transpose_zip(matrix):
    return [list(row) for row in zip(*matrix)]

# ทดสอบ
m = [[1, 2, 3], [4, 5, 6]]
print(transpose(m))       # [[1, 4], [2, 5], [3, 6]]
print(transpose_zip(m))   # [[1, 4], [2, 5], [3, 6]]

2. Matrix Addition

def add_matrix(a, b):
    return [[a[i][j] + b[i][j] for j in range(len(a[0]))] for i in range(len(a))]

m1 = [[1, 2], [3, 4]]
m2 = [[5, 6], [7, 8]]
print(add_matrix(m1, m2))  # [[6, 8], [10, 12]]

3. Matrix Multiplication

def mul_matrix(a, b):
    # a: m x n, b: n x p -> result: m x p
    return [[sum(a[i][k] * b[k][j] for k in range(len(b))) 
             for j in range(len(b[0]))] for i in range(len(a))]

m1 = [[1, 2], [3, 4]]
m2 = [[5, 6], [7, 8]]
print(mul_matrix(m1, m2))  # [[19, 22], [43, 50]]

ใช้ NumPy (แนะนำสำหรับงานจริง)

import numpy as np

# สร้าง Matrix
m = np.array([[1, 2, 3], [4, 5, 6]])
print(m.shape)  # (2, 3)

# Transpose
print(m.T)

# Operations
m1 = np.array([[1, 2], [3, 4]])
m2 = np.array([[5, 6], [7, 8]])
print(m1 + m2)      # Addition
print(m1 @ m2)      # Matrix Multiplication (Python 3.5+)
print(np.dot(m1, m2)) # Dot Product

# Inverse, Determinant, Eigenvalues
print(np.linalg.inv(m1))
print(np.linalg.det(m1))

เปรียบเทียบ List vs NumPy

FeatureNested ListNumPy Array
SyntaxManual loopsVectorized
PerformanceSlow (Python loops)Fast (C backend)
MemoryHigh overheadContiguous, efficient
Math OperationsManualBuilt-in