## 2017年12月11日月曜日

### 数学 - Python - 線形代数学 - 行列 – 行列の乗法(結合律)

ラング線形代数学(上)(S.ラング (著)、芹沢 正三 (翻訳)、ちくま学芸文庫)の3章(行列)、3(行列の乗法)、練習問題3.を取り組んでみる。

1. $\begin{array}{}\left(AB\right)C=\left(\begin{array}{cc}-1& 2\\ -2& 3\end{array}\right)\end{array}\left(\begin{array}{cc}1& 4\\ 2& 3\end{array}\right)=\left(\begin{array}{cc}3& 2\\ 4& 1\end{array}\right)A\left(BC\right)=\left(\begin{array}{cc}2& 1\\ 3& 1\end{array}\right)\left(\begin{array}{cc}1& -1\\ 1& 4\end{array}\right)=\left(\begin{array}{cc}3& 2\\ 4& 1\end{array}\right)$

2. $\begin{array}{}\left(AB\right)C=\left(\begin{array}{cc}1& 3\\ 11& 1\end{array}\right)\end{array}\left(\begin{array}{c}1\\ 3\end{array}\right)=\left(\begin{array}{c}10\\ 14\end{array}\right)A\left(BC\right)=\left(\begin{array}{ccc}2& 1& -1\\ 3& 1& 2\end{array}\right)\left(\begin{array}{c}4\\ 2\\ 0\end{array}\right)=\left(\begin{array}{c}10\\ 14\end{array}\right)$

3. $\begin{array}{}\left(AB\right)C=\left(\begin{array}{ccc}13& 7& 1\\ 0& 2& -5\end{array}\right)\end{array}\left(\begin{array}{cc}1& 2\\ 3& 1\\ -1& 4\end{array}\right)=\left(\begin{array}{cc}33& 37\\ 11& -18\end{array}\right)A\left(BC\right)=\left(\begin{array}{ccc}2& 4& 1\\ 3& 0& -1\end{array}\right)\left(\begin{array}{cc}4& 3\\ 6& 1\\ 1& 27\end{array}\right)=\left(\begin{array}{cc}33& 37\\ 11& -18\end{array}\right)$

コード(Emacs)

Python 3

#!/usr/bin/env python3
from sympy import pprint, symbols, Matrix

ABCs = [
(
[[2, 1],
[3, 1]],
[[-1, 1],
[1, 0]],
[[1, 4],
[2, 3]]
),
(
[[2, 1, -1],
[3, 1, 2]],
[[1, 1],
[2, 0],
[3, -1]],
[[1],
[3]]
),
(
[[2, 4, 1],
[3, 0, -1]],
[[1, 1, 0],
[2, 1, -1],
[3, 1, 5]],
[[1, 2],
[3, 1],
[-1, 4]]
)
]

for i, (a, b, c) in enumerate(ABCs):
print(f'({chr(ord("a") + i)})')
A = Matrix(a)
B = Matrix(b)
C = Matrix(c)
l = (A * B) * C
r = A * (B * C)
for t in [A, B, C, l, r, l == r]:
pprint(t)
print()
print()


$./sample3.py (a) ⎡2 1⎤ ⎢ ⎥ ⎣3 1⎦ ⎡-1 1⎤ ⎢ ⎥ ⎣1 0⎦ ⎡1 4⎤ ⎢ ⎥ ⎣2 3⎦ ⎡3 2⎤ ⎢ ⎥ ⎣4 1⎦ ⎡3 2⎤ ⎢ ⎥ ⎣4 1⎦ True (b) ⎡2 1 -1⎤ ⎢ ⎥ ⎣3 1 2 ⎦ ⎡1 1 ⎤ ⎢ ⎥ ⎢2 0 ⎥ ⎢ ⎥ ⎣3 -1⎦ ⎡1⎤ ⎢ ⎥ ⎣3⎦ ⎡10⎤ ⎢ ⎥ ⎣14⎦ ⎡10⎤ ⎢ ⎥ ⎣14⎦ True (c) ⎡2 4 1 ⎤ ⎢ ⎥ ⎣3 0 -1⎦ ⎡1 1 0 ⎤ ⎢ ⎥ ⎢2 1 -1⎥ ⎢ ⎥ ⎣3 1 5 ⎦ ⎡1 2⎤ ⎢ ⎥ ⎢3 1⎥ ⎢ ⎥ ⎣-1 4⎦ ⎡33 37 ⎤ ⎢ ⎥ ⎣11 -18⎦ ⎡33 37 ⎤ ⎢ ⎥ ⎣11 -18⎦ True$