1

I have a Vector, M, with size N and a Tensor, d, with size NxNxD.

My aim is to perform the matrix multication M*d[i,:,:] for each i to get a new matrix with size nxD.

Now I could just do it like this:

a = np.zeros((n,D))
for i in range(n):
    a[i] = G*np.matmul(M,d[i,:,:])

but I'd prefer a one line solution if it exists. Anyone got any ideas?

4
  • you could try to write it as list comprehension - and code would be in one line. OR you can put it in function and later you can execute function in one line (and you can reuse it in other places). OR maybe it has function .apply() to execute function on every row or column. Commented Jul 13 at 11:33
  • you could create minimal working code with small example data. It could be used to create answer. And it may show if you use torch, tensorflow or other module for tensor. Commented Jul 13 at 12:17
  • What? No? numpy is perfectly capable of dealing with tensors, and you definitely shouldn't use a comprehension. Commented Jul 13 at 12:39
  • @Reinderien I expected that numpy may do it directly but I don't know numpy that well to do it :) So I suggested other methods. Commented Jul 13 at 13:15

1 Answer 1

4

Don't use a loop or a comprehension. Use einsum:

G = 0.5
d = rand.integers(low=0, high=10, size=(3, 3, 2))
M = rand.integers(low=0, high=10, size=3)
a = G*np.einsum('ijk,j->ik', d, M)
print(a)
Sign up to request clarification or add additional context in comments.

1 Comment

Actually perfect, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.