Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

python - 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

question from:https://stackoverflow.com/questions/65939710/numpy-dot-product-of-a-stacked-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It sounds like you want

y1 * y2 + x1 * x2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...