How to multiply a lot of matrices without a loop?

Viewed 75

Suppose I have a numpy array of matricies

X = np.array([[[1.1, 2.1],
               [2.1, 1.1]],

              [[1.2, 2.2],
               [2.2, 1.2]],

              [[1.3, 2.3],
               [2.3, 1.3]]])

How do I make a matrix multiplication of all of them?

The problem comes from the function X = foo(a) that gives a matrix output. Once I calculate it on vector of length N, I have N matricies. Mathematically, I want to find this

ans = X[0] @ X[1] ... @ X[N-1]

For extremely large N loop approach is going to be slow :( So I want to vectorize it somehow.

Any help is appriciated!

1 Answers

numpy.linalg.multi_dot helps to multiply a sequence of matrices at once, and also internally optimizes the call order in order to reduce the number of computations required.

I also observe that there's a mathematical pattern in the sequence of matrices provided in question. If you could reduce it to a formula, then perhaps you could reduce the number of matrices needed to multiply.

Related