Suppose I have an arr = (n item array) and a matrix mat = nxm matrix. I want to multiply each item of arr with its aligned row of the matrix mat. How can I do it at numpy?
You would use broadcasting for this:
M = np.arange(1, 13).reshape(3, 4)
print M
# [[ 1 2 3 4]
# [ 5 6 7 8]
# [ 9 10 11 12]]
a = np.arange(1, 4)
print a
# [1, 2, 3]
# we broadcast a (3, 1) vector against a (3, 4) matrix
print a[...,None].shape, M.shape
# (3, 1) (3, 4)
print a[..., None] * M
# [[ 1 2 3 4]
# [10 12 14 16]
# [27 30 33 36]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.