python - Numpy submatrix operations -


i'm looking efficient way perform submatrix operations on larger matrix without resorting loops.

i'm doing operation (for 3x3 window):

newmatrix = numpy.zeros([numrows, numcols]) in range(1, numrows-1):     j in range(1, numcols-1):         sub = matrix[i-1:i+2, j-1:j+2]         newmatrix[i][j] = ... #do things sub matrix 

this considerably slower normal operations numpy matrices. there numpy has offer solve this, or hoping much?

edit: specific example

xweight = numpy.array([[-1./8, 0, 1./8], [-2./8, 0, 2./8], [-1./8, 0, 1./8]]) yweight = numpy.array([[1./8, 2./8, 1./8], [0, 0, 0], [-1./8, -2./8, -1./8]]) 

inside loop:

        dz_dx = numpy.sum(xweight * sub)         dz_dy = numpy.sum(yweight * sub) 

it seems me you're trying simple convolution?

def do(m):     rows, cols = m.shape     newmatrix = np.zeros_like(m)     in range(1, rows-1):         j in range(1, cols-1):             sub = matrix[i-1:i+2, j-1:j+2]             newmatrix[i][j] = numpy.sum(xweight * sub)     return newmatrix[1:-1, 1:-1] >>> res1 = do(matrix) >>> res2 = scipy.signal.convolve2d(matrix, xweight)[2:-2,2:-2] >>> np.allclose(np.abs(res1), np.abs(res2)) true 

didn't went details sign, should put on right track.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -