I have 4 matrices representing (x, y) components of vectors v1 and v2. Therefore matrices are x1, y1, x2, y2
.
Is it possible to compute dot product between arrays [x1_i, y1_i], [x2_i, y2_i]
, where i is just a single element index in all four arrays (which are all the same shape).
My solution so far is to stack them together and for loop over:
v1 = np.stack((y1, x1), axis=0)
v2 = np.stack((y2, x2), axis=0)
s = np.zeros(v1.shape[1:])
for i in range(v1.shape[1]):
for j in range(v1.shape[2]):
s[i,j] = np.dot(v1[:,i,j], v2[:,i,j])
Best solution would be to do a dot product over both elements in axis=0 for all elements in v1 and v2. Something like np.dot(v1,v2,axis=0)
x1.shape, y1.shape, x2.shape, y2.shape = (228, 192)
After stacking: v1.shape, v2.shape = (2, 228, 192)
Code where i1 and i2 are arrays from image (SimpleITK).
y1, x1 = np.gradients(i1)
y2, x2 = np.gradients(i2)
v1 = np.stack((y1, x1), axis=0)
v2 = np.stack((y2, x2), axis=0)
# this part is stupid
s = np.zeros(v1.shape[1:])
for i in range(v1.shape[1]):
for j in range(v1.shape[2]):
s[i,j] = np.dot(v1[:,i,j], v2[:,i,j])
Thank you for your help
question from:
https://stackoverflow.com/questions/65939710/numpy-dot-product-of-a-stacked-array