问题
I'm coming to python from Matlab. In Matlab, given two vectors that are not necessarily the same length, they can be added if one is a row vector and one is a column vector.
v1 = [1 3 5 7]
v2 = [2 4 6]'
v1 + v2
ans =
3 5 7 9
5 7 9 11
7 9 11 13
I am trying to produce the same behavior in python given two numpy arrays. Looping first came to mind:
import numpy as np
v1 = np.array([1,3,5,7])
v2 = np.array([2,4,6])
v3 = np.empty((3,4,))
v3[:] = np.nan
for i in range(0,3):
v3[i,:] = v1 + v2[i]
Is there a more concise and efficient way?
回答1:
import numpy as np
v1 = np.array([1, 3, 5, 7])
v2 = np.array([2, 4, 6])
v1 + v2[:, None]
You can read more about numpy's broadcasting rules.
回答2:
Try this out:
for i in v2:
z = []
for j in v1:
z.append(i+j)
print(z)
来源:https://stackoverflow.com/questions/63286737/numpy-summing-every-element-of-numpy-array-with-every-element-of-another