In Python I'm using the numpy package to do some math with matrices. In the code below I'm trying to calculate a new matrix from my orignal. xFactors and yFactors are both 3x3 matrices.
size = self.matrix.shape
for x in range(1, size[0] - 1):
for 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 is that this code is very inefficient. I tested te code with a 500x500 matrix and it takes up to two seconds. Do you have any ideas how I can optimize this code?
matrixas input data. So, look into Scipy's convolve2d.xFactorsandself.matrixare bothnumpy.arrayand notnumpy.matrix(in other words if OP is using element-wise multiplication and not matrix multiplication in calculatingnewXandnewYnumpy.array. @Divakar can you explain this a bit more? Do you mean the scipy method?