1

I have a group of matrices as below

import numpy as np
Number = 10
mylist = [np.random.randint(1, 5, size=(4, 4)) for i in range(Number)]

Now I want to matrix-multiply all matrices in mylist at once. Here value of Number may change

Is there any method/function available to perform this?

Brian Smith
  • 1,200
  • 4
  • 16
  • 2
    `np.linalg.multi_dot(mylist)`? 20x slower than `functools.reduce`, interesting. – Michael Szczesny Jun 10 '22 at 12:41
  • 2
    @MichaelSzczesny A great comment. Regarding `multi_dot` performance check out https://stackoverflow.com/q/45852228/1328439. In essence, `multi_dot` is best for large matrices where optimized multiplication order pays off. – Dima Chubarov Jun 10 '22 at 13:21
  • 1
    @DmitriChubarov - Thanks. I benchmarked only with `((n,n), float64)` matrices up to `(100,100,100)`. I didn't even notice the application to other suitable matrices. – Michael Szczesny Jun 10 '22 at 13:25
  • `multi_dot` is still doing repeated `dot`. Your arrays are all the same shape, so order doesn't matter. And the values are different, so you can't take advantage of grouping them (as a matrix power would). – hpaulj Jun 10 '22 at 16:27

3 Answers3

3

You can do that easily with the reduce function of the functools package:

import functools

result = functools.reduce(lambda a, b: a @ b, mylist)
Jérôme Richard
  • 41,678
  • 6
  • 29
  • 59
1

Consider using functools.reduce

import numpy as np
from functools import reduce
Number = 10
mylist = [np.random.randint(1, 5, size=(4, 4)) for i in range(Number)]
list_product = reduce(np.dot, mylist)

Here list_product would be a 4x4 matrix holding the product of the matrices in mylist.

Dima Chubarov
  • 16,199
  • 6
  • 40
  • 76
1

This functionality is native in the np.linalg package:

np.linalg.multi_dot(mylist)
Daniel F
  • 13,620
  • 2
  • 29
  • 55