Python Numpy.linalg.inv() - 逆矩陣

Jinku Hu 2023年1月30日 2020年6月17日
  1. numpy.linalg.inv() 語法
  2. 示例程式碼:numpy.linalg.inv() 方法
  3. 示例程式碼:numpy.linalg.inv() 方法與輸入矩陣
  4. 示例程式碼:numpy.square() 與矩陣陣列
Python Numpy.linalg.inv() - 逆矩陣

Numpy.linalg.inv() 計算給定矩陣的逆矩陣。

numpy.linalg.inv() 語法

numpy.linalg.inverse(arr) 

引數

arr 輸入陣列

返回值

返回給定矩陣的逆矩陣。

如果給定的矩陣不是正方形或者求逆矩陣失敗,它會引發錯誤。

示例程式碼:numpy.linalg.inv() 方法

import numpy as np

arr = np.array([[1, 3], [5, 7]])

arr_inv = np.linalg.inv(arr)

print(arr_inv)

輸出:

[[-0.875  0.375]
 [ 0.625 -0.125]]

示例程式碼:numpy.linalg.inv() 方法與輸入矩陣

如果給定的輸入是一個 numpy 矩陣,那麼 inv() 也返回一個矩陣。

import numpy as np

arr = np.matrix([[1, 3], [5, 7]])

arr_inv = np.linalg.inv(arr)

print(arr_inv, type(arr_inv))

輸出:

[[-0.875  0.375]
 [ 0.625 -0.125]] <class 'numpy.matrix'>

示例程式碼:numpy.square() 與矩陣陣列

import numpy as np

arr = np.array([
                [[1, 3],
                 [5, 7]],
                [[2, 5],
                 [4, 6]]])

arr_inv = np.linalg.inv(arr)

print(arr_inv)

輸出:

[[[-0.875  0.375]
  [ 0.625 -0.125]]

 [[-0.75   0.625]
  [ 0.5   -0.25 ]]]

如果輸入陣列由多個矩陣組成,numpy linalg.inv() 方法一次計算它們的逆矩陣。

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn