Cilenco
Cilenco

Reputation: 7179

Inefficient numpy code

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?

Upvotes: 0

Views: 141

Answers (1)

chthonicdaemon
chthonicdaemon

Reputation: 19830

If xFactors and self.matrix are both numpy.array and not numpy.matrix (in other words if you are using element-wise multiplication and not matrix multiplication in calculating newX and newY), then this should do the same thing a lot faster:

from scipy.signal import convolve2d

self.newMatrix = convolve2d(self.matrix, xFactors + yFactors, mode='valid')

In the original code, it was not clearly stated that xFactors and yFactors were square. If they weren't one would need to make them square by repeating them as needed if the above addition doesn't broadcast correctly.

Upvotes: 2

Related Questions