1

I have two arrays that look as follows:

enter image description here

In code that is:

t = np.random.rand(6, 6, 2)

I now want to compute the dot product of the axis 2 arrays (the ones of shape 2), for each of the entries of the axis 0 and 1 arrays.

I can do it with a for loop:

Q = np.zeros_like(t)
for i in range(6):
    for j in range(6):
        Q[i,j] = t[i,j].dot(t[i,j])

How can I do this with numpy functions?

I could not get it to work with .dot, .tensordot or similar methods...

t.dot(t) produces this error ValueError: shapes (6,6,2) and (6,6,2) not aligned: 2 (dim 2) != 6 (dim 1) which is to be expected, however I would like to circumvent it.

charelf
  • 3,103
  • 4
  • 29
  • 51

2 Answers2

0

Since you're taking the dot product of all rows with themselves, you can simplify to a multiplication of t with itself and adding the result. In order to have the same shape as t, you can use np.broadcast_to:

np.broadcast_to((t*t).sum(-1)[...,None], t.shape)

Update

Based on the comments, it appears that you just need:

(t*t).sum(-1)

Check:

np.allclose(Q, np.broadcast_to((t*t).sum(-1)[...,None], t.shape))
# True
yatu
  • 86,083
  • 12
  • 84
  • 139
  • Thank you for your answer, however I got it working with an, in my opinion, easier approach. Sorry for the inconveniences. – charelf Jun 02 '20 at 10:24
  • Your approach produces a different result to `Q`, which I assumed to be the expected output. Meaning that my answer can be simplified to `(t*t).sum(-1)`, which seems quite a simple approach IMO @charel-f – yatu Jun 02 '20 at 10:55
  • Oh I see, I must have messed up my arrays since I was using a different array while doing the exercise then the one used to ask my question. Sorry – charelf Jun 02 '20 at 12:42
0

I got it working with np.einsum:

np.einsum("...i, ...i", t, t)

which produces the same output as my for loop.

charelf
  • 3,103
  • 4
  • 29
  • 51