Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Numpy matrix multiplication using loop to multiply multiple matrices together

I have written code which creates matrices with name matrixi, where i is replaced with the current loop number:

for i in range(len(node2)):
    if sOrP[i] == 'S':
        #print('series connection')
        matrixTemplate = numpy.array([[1.0, 0.0], [0.0, 1.0]])  #Got to put 1.0 else it doesnt work
        matrixTemplate[0][1] = frequenciesList[0][i]
        globals()['matrix%s' % i] = matrixTemplate
        #print(matrixTemplate)
    elif sOrP[i] == 'P':
        #print('parallel connection')
        matrixTemplate = numpy.array([[1.0, 0.0], [0.0, 1.0]])
        matrixTemplate[1][0] = 1 / frequenciesList[0][i]
        globals()['matrix%s' % i] = matrixTemplate
        #print(matrixTemplate)

I then need to multiply the created matrices together:

Ty = matrix0 @ matrix1 @ matrix2 @ matrix3 @ matrix4 @ matrix5 @ matrix6 @ matrix7 @ matrix8 @ matrix9

This works but the code has to be able to take multiple inputs with potentially more or fewer matrices being created. In that case it wouldn't work.

Would it be possible to do the multiplication part using a loop or function?

like image 529
Dan Avatar asked Aug 08 '26 16:08

Dan


1 Answers

You could use a list (or a dictionary) to hold your matrices:

matrices = []

for i in range(len(node2)):

    if (sOrP[i] == 'S'):
        #print('series connection')
        matrixTemplate = numpy.array([[1.0, 0.0],[0.0, 1.0]]) #Got to put 1.0 else it doesnt work

        matrixTemplate[0][1] = frequenciesList[0][i]

        matrices.append(matrixTemplate)

        #print(matrixTemplate)

    elif (sOrP[i] == 'P'):
        #print('parallel connection')
        matrixTemplate = numpy.array([[1.0, 0.0],[0.0, 1.0]])

        matrixTemplate[1][0] = 1/frequenciesList[0][i]

        matrices.append(matrixTemplate)

        #print(matrixTemplate)

And then use reduce and numpy.matmul to compute your total matrix product:

from functools import reduce

Ty = reduce(numpy.matmul, matrices)
like image 64
dzang Avatar answered Aug 11 '26 04:08

dzang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!