Home > OS >  Matrix multiplication with variable number of matrices
Matrix multiplication with variable number of matrices

Time:06-10

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?

CodePudding user response:

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

import functools

result = functools.reduce(lambda a, b: a @ b, mylist)

CodePudding user response:

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.

  • Related