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

วิธีใช้ SciPy คำนวณ Inverse ของ Matrix ใน Python

บางครั้งต้องคำนวณ inverse ของ matrix ใช้สำหรับการคำนวณต่อ ขั้นตอนหา inverse ด้วยมือ: 1) หา minors (determinant ของ submatrix) 2) หา cofactors (สลับเครื่องหมาย) 3) transpose 4) หารด้วย determinant ของ matrix ต้นฉบับ

SciPy มีฟังก์ชัน 'inv' ใน 'linalg' ช่วยคำนวณง่ายขึ้น

Syntax 'inv'

scipy.linalg.inv(matrix)

ตัวอย่าง

from scipy import linalg
import numpy as np
two_d_matrix = np.array([
    [7, 9],
    [33, 8]
])
print("The inverse of the matrix is :")
print(linalg.inv(two_d_matrix))

ผลลัพธ์

The inverse of the matrix is :
[[-0.03319502 0.0373444 ]
 [ 0.13692946 -0.02904564]]

คำอธิบาย

  • นำเข้าไลบรารี
  • กำหนด matrix ค่าตัวเลข
  • ส่งพารามิเตอร์ให้ 'inv' คำนวณ inverse
  • เรียกฟังก์ชันและแสดงผล

Matrix inverse ใช้แก้ระบบสมการเชิงเส้น A⁻¹A = I ต้องเป็น square matrix และ non-singular (det ≠ 0)