Numpy has a function that automatically converts to an appropriate form when performing operations between matrices with different dimensions, and this is called broadcasting. I think it's faster to see it, so I'll write it below.
A = np.array([1, 2, 3, 4, 5])
print(f'{"="*20}A')
print(A)
print(f'{"="*20}A-1')
# (1, 5)Matrix and scalar value arithmetic
print(A - 1)
====================A
[1 2 3 4 5]
====================A-1
[0 1 2 3 4]
Numpy automatically adjusts the dimensions when performing operations on matrices with different dimensions. For example, the operation of $ (m, n) + (1, n) $ expands $ (1, n) $ and converts it to $ (m, n) $.
A = np.array([
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]])
B = np.array([1, 2, 3, 4, 5])
print(f'{"="*20}A')
print(A)
print(f'{"="*20}B')
print(B)
print(f'{"="*20}A - B')
print(A - B)
====================A
[[ 1 2 3 4 5]
[ 6 7 8 9 10]]
====================B
[1 2 3 4 5]
====================A - B
[[0 0 0 0 0]
[5 5 5 5 5]]
Recommended Posts