LoginSignup
6
6

More than 5 years have passed since last update.

NumPyで行列演算をしてみる

Last updated at Posted at 2015-12-17

岩手県立大学アドベントカレンダー17日目です!お疲れ様です、Jack (@kazuhikoyamashita)です。
最近のマイブームはPythonです。今回は、numpyを利用して行列演算をしてみます。

NumPyとは

NumPyとは、数値計算を行うための拡張モジュールです。
詳細は下記リンクをご覧ください。
http://www.numpy.org/

pipをインストールしましょう

numpyをインストールするには、pipコマンドが必要です。
pipコマンドをインストールするには、easy_installでインストールしましょう。
下記コマンドを入力してください。

% easy_install pip 

pipコマンドでnumpyをインストールする

numpyをインストールするには、下記コマンドを実行します。
今回インストールされたnumpyのバージョンは1.10.2です。

% pip install numpy
Collecting numpy
  Downloading numpy-1.10.2-cp35-cp35m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (3.7MB)
    100% |████████████████████████████████| 3.7MB 133kB/s 
Installing collected packages: numpy
Successfully installed numpy-1.10.2

使ってみる

m1とm2という行列を用意し、和差積商とm1の逆行列を求めてみます。
プログラムは下記となります。

# -*- coding: utf-8 -*-
import numpy as np
from numpy import linalg as la

m1 = np.matrix('1 2; 3 4')
m2 = np.matrix('5 6; 7 8')

# 和
print("#### 和")
print(m1 + m2)

# 差
print("#### 差")
print(m1 - m2)

# 要素同士の積
print("#### 要素同士の積")
print(m1 * m2)

# 要素同士の商
print("#### 要素同士の商")
print(m1 / m2)

# m1の逆行列
print("#### m1の逆行列")
print(la.inv(m1))

出力結果は下記となります。
逆行列が簡単に計算できて便利ですね。

% python sample.py
#### 和
[[ 6  8]
 [10 12]]
#### 差
[[-4 -4]
 [-4 -4]]
#### 要素同士の積
[[19 22]
 [43 50]]
#### 要素同士の商
[[ 0.2         0.33333333]
 [ 0.42857143  0.5       ]]
#### m1の逆行列
[[-2.   1. ]
 [ 1.5 -0.5]]

以上!

6
6
1

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
6
6