Cilenco - 7 months ago 50

Python Question

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`

`yFactors`

`3x3`

`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`

Answer

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.

Source (Stackoverflow)