2019年1月29日火曜日

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

ラング線形代数学(上)(S.ラング (著)、芹沢 正三 (翻訳)、ちくま学芸文庫)の3章(行列)、2(行列の乗法)、練習問題3の解答を求めてみる。

1. $\begin{array}{}\left(AB\right)C\\ =\left[\begin{array}{cc}-1& 2\\ -2& 3\end{array}\right]\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]\end{array}$

2. $\begin{array}{}\left(AB\right)C\\ =\left[\begin{array}{cc}1& 3\\ 11& 1\end{array}\right]\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]\end{array}$

3. $\begin{array}{}\left(AB\right)C\\ =\left[\begin{array}{ccc}13& 7& 1\\ 0& 2& -5\end{array}\right]\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]\end{array}$

コード

Python 3

#!/usr/bin/env python3
from sympy import pprint, symbols, Matrix
print('3.')

ts = [([[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(ts):
print(f'({chr(ord("a") + i)})')
A = Matrix(a)
B = Matrix(b)
C = Matrix(c)
for t in [(A * B) * C, A * (B * C)]:
pprint(t)
print()
print()


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