0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Pythonで行列を扱うときの基本操作をまとめる

Posted at

今回はPythonで行列を用いたシミュレーションを行うときに便利な基本操作についてコマンドとその実行結果をまとめる

まずはライブラリのインポート

import numpy as np

numpynpとして使います

一次元配列の生成

a=np.array([1,2,3])
a
array([1, 2, 3])

2つの配列を垂直方向、水平方向へ結合

vstackが垂直方向、hstackが水平方向

b=np.array([4,5,6])
c=np.vstack((a,b))
d=np.hstack((a,b))
c,d
(array([[1, 2, 3],
        [4, 5, 6]]),
 array([1, 2, 3, 4, 5, 6]))

多次元配列の生成と行列の積

e=np.array([[1,3,5],[2,4,6]])
f=np.array([[1,2],[3,4],[5,6]])
np.dot(e,f)
array([[35, 44],
       [44, 56]])

np.dot(A,B)

A×B

配列の形の確認、変形

g=np.array([[1,2,3],[4,5,6]])
print(g.shape)
g.reshape(3,2)
(2, 3)
array([[1, 2],
       [3, 4],
       [5, 6]])

一次元配列への変換と注意

print(g.ravel())
g.reshape(1,-1)

reshape(1,-1)-1は列を自動で最適にしてくれるという意味

[1 2 3 4 5 6]
array([[1, 2, 3, 4, 5, 6]])

注意:一次元配列(前者)と行数が1の二次元配列(後者)は違う

逆行列の算出とその確認

h=np.array([[1,0,0],[0,2,0],[0,0,3]])
h_inv=np.linalg.inv(h)
np.dot(h_inv,h)
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

逆行列と元の行列をかけて単位行列が得られることを確認

固有値と固有ベクトルの算出と確認

i=np.array([[0,2],[1,3]])
eig=np.linalg.eig(i)
eig
(array([-0.56155281,  3.56155281]),
 array([[-0.96276969, -0.48963374],
        [ 0.27032301, -0.87192821]]))

1行目eig[0]に固有値、2行目eig[1]に固有ベクトル
それぞれの固有ベクトルは列で返される

print(np.dot(i,eig[1][:,0]))
eig[0][0]*eig[1][:,0]
[ 0.54064603 -0.15180065]
array([ 0.54064603, -0.15180065])

行列$A$の固有値$\lambda$と固有ベクトル$\vec x$について

A\vec x=\lambda \vec x

が成り立つことを確認

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?