Stephen Summerhayes
Stephen Summerhayes

Reputation: 3

element wise matrix multiplication python

Hi I'm stuck on what on the face of it seems a simple problem, so I must be missing something!

I have a list (of indeterminate length) of matrices calculated from user values. - ttranspose

I also have another single matrix, Qbar which I would like to multiply (matrix form) each of the matrices in ttranspose, and output a list of the resultant matrices. << Which should be the same length as ttranspose.

            def Q_by_transpose(ttranspose, Qmatrix):
                Q_by_transpose = []
                for matrix in ttranspose:
                    Q_by_transpose_ind = np.matmul(ttranspose, Qmatrix)
                    Q_by_transpose.append(Q_by_transpose_ind)
                return (Q_by_transpose)

Instead when I test this with a list of 6 matrices (ttranspose) I get the a long list of mtrices, which appears to be in 6 arrays (as expected) but each array is made up of 6 matrices?

Im hoping to create a list of matrices for which I would then perform elementwise multiplication between this and another list. So solving this will help on both fronts!

Any help would be greatly appreciated!

I am new to Python and Numpy so am hopeful you guys will be able to help!

Thanks

Upvotes: 0

Views: 612

Answers (1)

FCo
FCo

Reputation: 505

It appears that instead of passing a single matrix to the np.matmul function, you are passing the entire list of matrices. Instead of

for matrix in ttranspose:
    Q_by_transpose_ind = np.matmul(ttranspose, Qmatrix)
    Q_by_transpose.append(Q_by_transpose_ind)

do this:

for matrix in ttranspose:
    Q_by_transpose_ind = np.matmul(matrix, Qmatrix)
    Q_by_transpose.append(Q_by_transpose_ind)

This will only pass one matrix to np.matmul instead of the whole list. Essentially what you're doing right now is multiplying the entire list of matrices n times, where n is the number of matrices in ttranspose.

Upvotes: 1

Related Questions