Posted at

# Numpyで実装する線形代数の行列

## 行列の足し算

\begin{pmatrix}
2 & 4 \\
0 & 4 \\
7 & 9 \\
3 & 7
\end{pmatrix}
+
\begin{pmatrix}
9 & 2 \\
4 & 1 \\
1 & 7 \\
0 & 2
\end{pmatrix}
=
\begin{pmatrix}
11 & 6 \\
4 & 5 \\
8 & 16 \\
3 & 9
\end{pmatrix}


それぞれが違う行と列では計算はできない

2 x 3の行列と4 x 2の行列の足し算は不可能

\begin{pmatrix}
1 & 3 & 7 \\
2 & 9 & 0 \\
\end{pmatrix}

+

\begin{pmatrix}
9 & 2 \\
4 & 1 \\
1 & 7 \\
0 & 2
\end{pmatrix}



import numpy as np

arr1 = np.array([[2, 4], [0, 4], [7, 9], [3, 7]])
arr2 = np.array([[9, 2], [4, 1], [1, 7], [0, 2]])

print(arr1)
# [[2 4]
#  [0 4]
#  [7 9]
#  [3 7]]

print(arr2)
# [[9 2]
#  [4 1]
#  [1 7]
#  [0 2]]

result = arr1+arr2
print(result)
# [[11  6]
#  [ 4  5]
#  [ 8 16]
#  [ 3  9]]



## 行列のスカラー倍

それぞれの値を定数倍する。

6
\times
\begin{pmatrix}
1 & 3 & 7 \\
2 & 9 & 0 \\
\end{pmatrix}

=
\begin{pmatrix}
6 & 18 & 42 \\
12 & 54 & 0 \\
\end{pmatrix}



import numpy as np

arr1 = np.array([[1, 3, 7], [2, 9, 0]])
print(arr1)
# [[1 3 7]
#  [2 9 0]]

result = arr1 * 6
print(result)
# [[ 6 18 42]
#  [12 54  0]]



\begin{pmatrix}
6 & 3 \\
0 & 1 \\
\end{pmatrix}
\div
3
=
\begin{pmatrix}
6 & 3 \\
0 & 1 \\
\end{pmatrix}
\times
\frac{1}{3}
=
\begin{pmatrix}
2 & 1 \\
0 & 1/3 \\
\end{pmatrix}



import numpy as np

arr1 = np.array([[6, 3], [0, 1]])
print(arr1)
# [[6 3]
#  [0 1]]

result = arr1 / 3
print(result)
# [[ 2 1]
#  [ 0 0.33333333]]



5
\times
\begin{pmatrix}
2 \\
1 \\
0 \\
3 \\
\end{pmatrix}
-
\begin{pmatrix}
4 \\
2 \\
3 \\
1 \\
\end{pmatrix}
+
\begin{pmatrix}
6 \\
0 \\
3 \\
12 \\
\end{pmatrix}
\div
6
\\

=
\begin{pmatrix}
10 \\
5 \\
0 \\
15 \\
\end{pmatrix}
-
\begin{pmatrix}
4 \\
2 \\
3 \\
1 \\
\end{pmatrix}
+
\begin{pmatrix}
1 \\
0 \\
1/2 \\
2 \\
\end{pmatrix}
\\


=
\begin{pmatrix}
7 \\
3 \\
-2.5 \\
16 \\
\end{pmatrix}