Erogol Erogol - 1 year ago 146
Python Question

Iterating over Numpy matrix rows to apply a function each?

I want to be able to iterate over the matrix to apply a function to each row. How can I do it for a Numpy matrix ?

Answer Source

Use numpy.apply_along_axis(). Assuming your matrix is 2D, you can use like:

import numpy as np
mymatrix = np.matrix([[11,12,13],
def myfunction( x ):
    return sum(x)

print np.apply_along_axis( myfunction, axis=1, arr=mymatrix )
#[36 66 96]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download