简体   繁体   中英

How to apply function of multiple matrices to each element of a list of matrices with python numpy?

For sake of simplicity lets define the function to do only matrix multiplication:

f(matrix1, matrix2):
    #assume that matrix1.shape == np.transpose(matrix2).shape
    #both are 1 dimensional so this returns a scalar
    return matrix1 * matrix2 

Now lets say I want to run this function a bunch of times for getting a sum:
- matrix1 - different each time
- matrix2 - same each time

I could write a for loop:

matrix_a1 = np.matrix([1,2])
matrix_a2 = np.matrix([3,4])
matrix_list = [matrix_a1, matix_a2]
matrixb = np.matrix([5,6],[7,8])
total = 0
for matrix in matrix_list
    total+= f(matrix, matrixb)

I want to write it like this:

sum(f(matrix_list, matrixb))

But this doesn't work because it tries to do matrix multiplication between matrix_list and matrixb instead of iterating over matrix_list.

How to I iterate over the matrix_list using numpy?

You convert your list of matrices to a multidimensional array.

That will be easier if you step out of the comfort of the matrix object and go with plain arrays. Your first function, when given two arrays, can be rewritten with np.dot as:

def f(array1, array2) :
    return np.dot(array1, array2)

You can now do:

>>> array_a1 = np.array([1, 2])
>>> array_a2 = np.array([3, 4])
>>> array_a = np.array([array_a1, array_a2])
>>> array_a
array([[1, 2],
       [3, 4]])
>>> array_b = np.array([[5, 6], [7, 8]])
>>> array_b
array([[5, 6],
       [7, 8]])
>>> f(array_a, array_b)
array([[19, 22],
       [43, 50]])
>>> np.sum(f(array_a, array_b), axis=0)
array([62, 72])

You could even do :

>>> array_a1 = np.array([[1, 2], [3, 4]])
>>> array_a2 = np.array([[5, 6], [7, 8]])
>>> array_a = np.array([array_a1, array_a2])
>>> array_b = np.array([[9, 10], [11, 12]])
>>> np.sum(f(array_a, array_b), axis=0)
array([[142, 156],
       [222, 244]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM