[Python]行列の掛け算
dotメソッドを使う。最後の例のとおり、掛けられる行列の列数と掛ける行列の行数が同じでなければ計算することはできない。
>>> mx1 = np.array([[-1, 0, 3], [8, 1, -5]])
>>> mx2 = np.array([[3, 4, 0], [-2, 1, 2]])
>>> mx3 = np.array([[4, -3, 7], [2, 0, -1], [1, 5, 0]])
>>> print(mx1)
[[-1 0 3]
[ 8 1 -5]]
>>> print(mx2)
[[ 3 4 0]
[-2 1 2]]
>>> print(mx3)
[[ 4 -3 7]
[ 2 0 -1]
[ 1 5 0]]
>>> np.dot(mx1, mx3)
array([[ -1, 18, -7],
[ 29, -49, 55]])
>>> np.dot(mx2, mx3)
array([[ 20, -9, 17],
[ -4, 16, -15]])
>>> np.dot(mx1, mx2)
Traceback (most recent call last):
File "", line 1, in
File "<__array_function__ internals>", line 5, in dot
ValueError: shapes (2,3) and (2,3) not aligned: 3 (dim 1) != 2 (dim 0)