0

Let's generate a 'list of three 2x2 matrices' that I call M1, M2 and M3:

import numpy as np
arr = np.arange(4*2*2).reshape((3, 2, 2))

I want to take the dot product of all these matrices:

 A = M1 @ M2 @ M3

What's the easiest and fastest way to do this? I'm basically looking for something similar to '.sum(axis=0)', but for matrix multiplication.

Pickniclas
  • 349
  • 1
  • 8

1 Answers1

1

You are probably looking for np.linalg.multi_dot:

arr = np.arange(3*2*2).reshape((-1, 2, 2))
np.linalg.multi_dot(arr)

Will give you the dot product between arr[0], arr[1] and arr[2]. As would arr[0] @ arr[1] @ arr[2].

Ivan
  • 34,531
  • 8
  • 55
  • 100
  • Thanks! Exactly what I was looking for. – Pickniclas Dec 05 '20 at 18:11
  • 1
    For 3 arrays `multi_dot` uses `np.linalg.linalg._multi_dot_three` which does `dot(dot(A, B), C, out=out)` (or the alternate grouping if shapes differ). So if the arrays are all the same shape, `multi_dot` is no better a chained `dot` (or `@`). – hpaulj Dec 05 '20 at 18:58