Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

NumPy:線形代数

ベクトルや行列の演算をまとめる. 理論形態学(P2-01)の回転・座標変換や,平衡点の安定性解析(ヤコビ行列 (Jacobian matrix)の固有値)で用いる.

import numpy as np

a = np.array([1, 2, 3])
b = np.array([6, 3, 1])
C = np.array([[1, 5, 6], [7, 8, 9], [4, 2, 3]])
D = np.array([[2.3, 4, 7.2], [7, 9, 1], [11, 2, 9]])

ベクトルの演算

内積 (dot product)np.dot外積 (cross product)np.cross で計算する.

print("内積 a・b:", np.dot(a, b))
print("外積 a×b:", np.cross(a, b))
print("ノルム |a|:", np.linalg.norm(a))
内積 a・b: 15
外積 a×b: [-7 17 -9]
ノルム |a|: 3.7416573867739413

行列の積

* は要素ごとの積である点に注意する.行列としての積(行列積)は np.dot または @ 演算子を使う.

print("要素ごとの積 C * D:\n", C * D)
print("行列積 C @ D:\n", C @ D)
print("行列とベクトルの積 C @ a:", C @ a)
要素ごとの積 C * D:
 [[ 2.3 20.  43.2]
 [49.  72.   9. ]
 [44.   4.  27. ]]
行列積 C @ D:
 [[103.3  61.   66.2]
 [171.1 118.  139.4]
 [ 56.2  40.   57.8]]
行列とベクトルの積 C @ a: [29 50 17]

転置は .T または np.transpose で得られる.

print("転置 C.T:\n", C.T)
転置 C.T:
 [[1 7 4]
 [5 8 2]
 [6 9 3]]

単位行列・行列式・逆行列・固有値

単位行列 (identity matrix)行列式 (determinant)逆行列 (inverse matrix)固有値 (eigenvalue)などを求める関数は np.linalg にまとまっている.

# 単位行列
I = np.identity(3)
print("単位行列 I:\n", I)

# 行列式
print("行列式 det(D):", np.linalg.det(D))

# 逆行列
print("逆行列 inv(C):\n", np.linalg.inv(C))
単位行列 I:
 [[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
行列式 det(D): -638.3000000000005
逆行列 inv(C):
 [[-0.22222222  0.11111111  0.11111111]
 [-0.55555556  0.77777778 -1.22222222]
 [ 0.66666667 -0.66666667  1.        ]]

固有値・固有ベクトルは np.linalg.eig,固有値だけなら np.linalg.eigvals で求める. 平衡点の安定性解析(ヤコビ行列の固有値)で用いる.

eigenvalues, eigenvectors = np.linalg.eig(C)
print("固有値:", eigenvalues)
print("固有ベクトル(列ごと):\n", eigenvectors)
固有値: [14.72735221 -3.28537742  0.55802521]
固有ベクトル(列ごと):
 [[ 0.43801562  0.85468529 -0.00703173]
 [ 0.84944136 -0.12913467 -0.76794748]
 [ 0.29426465 -0.50282928  0.64047421]]