I'm a beginner to coding and have been trying to operate on matrices for a bit, but got stuck at a point. I've got a 224x224 matrix of integers and need to apply a function over 8x8 patches of the matrix, individually. (28 patches, each 8x8) How do I do this?
            Asked
            
        
        
            Active
            
        
            Viewed 99 times
        
    0
            
            
        - 
                    So you think this looks the same for all kinds of matrix-implementions? There is no native matrix in python. – sascha Mar 22 '17 at 18:02
- 
                    It's an integer matrix. Edited. Thanks for reminding – VSCodes Mar 22 '17 at 18:04
- 
                    1That is the least of parameters that matter. Just calculate your stride-size and do a nested for-loop. For optimized implementations, checkout skimage's ```view_as_blocks``` (numpy-array based). – sascha Mar 22 '17 at 18:04
- 
                    2What do you mean by "matrix". Again *there is no native matrix in Python*. So what, exactly, are you referring to as a "matrix?" A list-of-lists? Some kind of `numpy` array? – juanpa.arrivillaga Mar 22 '17 at 18:11
- 
                    Is it a [matrix](http://stackoverflow.com/questions/6667201/how-to-define-two-dimensional-array-in-python) as the one defined in that answer, a nested list, a dictionary or a numpy array? Matrix is not in native python. Please clarify your question. – Mr. Xcoder Mar 22 '17 at 18:13
- 
                    You'll have to post some code. If you're using `numpy`, your matrices might look one way. If you're using pure python, you might mean `matrix[i][j]`. They are different, and the answers you get will be different, because of that. – aghast Mar 22 '17 at 18:16
- 
                    Also, did you mean 784 patches, each 8x8? Because 224x224 / 8x8 = 28x28. – aghast Mar 22 '17 at 18:18
1 Answers
0
            
            
        Here's one way:
# Just make up a 224x224 matrix
Matrix = [ [row*col for col in range(224)] for row in range(224)]
def f(m, r, c):
    for row in range(r, r+8):
        for col in range(c, c+8):
            m[row][col] += 1    # whatever operation goes here
def apply_func_to_matrix_by_8(m, f):
    nr = len(m)
    nc = len(m[0])
    for row in range(0, nr, 8):
        for col in range(0, nc, 8):
            f(m, row, col)
apply_func_to_matrix_by_8(Matrix, f)
 
    
    
        aghast
        
- 14,785
- 3
- 24
- 56
