Accessing ndarray and discarding invalid positions - Python
Question: I have one question about accessing a matrix position that in fact does not
exists.

First, I have an matrix with **rows** rows and **cols** columns. From this
matrix, I have to get sets of **n** x **n** sub matrices. For example, to get
3 x 3 sub matrices, I do the following:

    
    
    for x, y in product(range(1, matrix.rows-1), range(1, matrix.cols-1)):
        bootstrap_3x3 = npr.choice(matrix.data[x-1:x+2, y-1:y+2].flatten(), size=(3, 3), replace=True)
    

But, as can be seen, I'm not considering the extremes, and I have to. For x =
0 and y = 0, for example, I should consider `matrix.data[x:x+2, y:y+2]` (the
center should be the current x and y), returning a `3 x 3` with the first
row/column = 0.

I know that I can achieve this with some **if** statements. But I guess Python
should have a clever way to do this properly.

Thank you in advance.


Answer: I would make a new matrix, padded with `(n-1)/2` zeros around it:

    
    
    import numpy as np
    
    rows, cols = 4, 6
    n = 3
    d = (n-1)/2
    data = np.arange(rows*cols).reshape(rows, cols)
    padded = np.pad(data, d, mode='constant')
    for x, y in  np.indices(data.shape).reshape(2, -1).T:
        sub = padded[x:x+n, y:y+n]
        print sub
        bootstrap_nxn = np.random.choice(sub.ravel(), (n, n))
    

This assumes `n` is odd, and that the submatrix _center_ is always within the
the original `data` matrix. If `n` is even, the _center_ of the submatrix
isn't well defined.

If you actually want to have the submatrix overlap with the data matrix with
only one row, then you'd need to pad with `n-1` zeros (and in that case even
vs odd `n` won't matter).

