[Python]行列の和と差を求める
ndarray型に+演算子または-演算子を使う。行列の和と差の定義(行の数と列の数が同じ行列同士の各成分を足す、引く)から、二つの行列の行数と列数が一致しない場合はエラーが発生する。
>>> import numpy as np
>>> mxaa1 = np.array([[1, 2, 3], [6, 4, 2]])
>>> mxbb1 = np.array([[1, 1, 0], [2, 3, 8]])
>>> print(mxaa1)
[[1 2 3]
[6 4 2]]
>>> print(mxbb1)
[[1 1 0]
[2 3 8]]
>>> mxaa1 + mxbb1
array([[ 2, 3, 3],
[ 8, 7, 10]])
>>> mxaa2 = np.array([[1, 3], [2, 4]])
>>> mxbb2 = np.array([[7, 9], [5, 1]])
>>> print(mxaa2)
[[1 3]
[2 4]]
>>> print(mxbb2)
[[7 9]
[5 1]]
>>> mxaa2 - mxbb2
array([[-6, -6],
[-3, 3]])
>>> mxaa1 + mxbb2
Traceback (most recent call last):
File "", line 1, in
ValueError: operands could not be broadcast together with shapes (2,3) (2,2)
>>> mxaa1 - mxbb2
Traceback (most recent call last):
File "", line 1, in
ValueError: operands could not be broadcast together with shapes (2,3) (2,2)




