简体   繁体   中英

Numpy dot product of a stacked array

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

It sounds like you want

y1 * y2 + x1 * x2

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM