python - Inefficient numpy code -


in python i'm using numpy package math matrices. in code below i'm trying calculate new matrix orignal. xfactors , yfactors both 3x3 matrices.

size = self.matrix.shape  x in range(1, size[0] - 1):     y in range(1, size[1] - 1):         submatrix = self.matrix[x-1:x+2, y-1:y+2]          newx = (xfactors * submatrix).sum()         newy = (yfactors * submatrix).sum()          self.newmatrix[x-1][y-1] = newx + newy 

my problem code inefficient. tested te code 500x500 matrix , takes 2 seconds. have ideas how can optimize code?

if xfactors , self.matrix both numpy.array , not numpy.matrix (in other words if using element-wise multiplication , not matrix multiplication in calculating newx , newy), should same thing lot faster:

from scipy.signal import convolve2d  self.newmatrix = convolve2d(self.matrix, xfactors + yfactors, mode='valid') 

in original code, not stated xfactors , yfactors square. if weren't 1 need make them square repeating them needed if above addition doesn't broadcast correctly.


Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -