Integrals - 1 year ago 64

Python Question

The code below works correctly for a very specific case as I describe below. I want to generalize it. I am trying to print out sub arrays of arrays.

`import numpy as np`

alpha = input("input this number... ")

X = np.arange(alpha**2).reshape(alpha,alpha) #square matrix

beta = input("a number in the matrix X")

if(beta > alpha**2):

print("must pick number inside array"), exit()

print(X) #correct square matrix

00 01 02 03 04

05 06 07 08 09

10 11 12 13 14

15 16 17 18 19

20 21 22 23 24

I want to print a 3x3 sub array of this matrix X, independent of what I choose alpha to be (independent of a 3x3 square or 5x5 square matrix,etc). As shown below.

Answer Source

If all values in the array are unique (as they are in both examples in your question):

```
[[i,j]] = numpy.argwhere(X==beta)
print(X[i-1:i+2,j-1:j+2])
```

This code finds `(i, j)`

indices in the 2D array such that `X[i,j]`

is equal to `beta`

value. And therefore `X[i-1:i+2,j-1:j+2]`

is 3x3 array with `beta`

value in the center unless `beta`

is on the edges of the matrix.

To get all available values even on the edges:

```
print(X[max(i-1,0):i+2,max(j-1,0):j+2])
```