0

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.

2 Answers 2

1

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])
Sign up to request clarification or add additional context in comments.

3 Comments

@Integrals what is edge? It is i == 0 or j == 0 or i == (alpha - 1) or j == (alpha - 1).
@Integrals It is very basic. The code in the answer shows how to get (i,j) indices. The explicit conditions in my previous comment show how to find out whether beta is on the edge (by checking its indices: i,j). If you don't understand my comment; ask a separate question about how to detect that the input value beta is on the edge of the square numpy array.
@Integrals my comment uses or between conditions that works as is: you should not have replaced it with commas. You should read a book (any book) on Python. It will save you time to avoid being stuck on trivial issues. There is a list of free books in the Python tag description
1

You can try:

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() 
row, col = beta // alpha, beta % alpha # This will give you the idxs of beta number in array
subsize = input("a size of submatrix you want to get")
border = (subsize - 1) // 2

subrand = np.array(X)[row - border: row + border + 1, col - border: col + border + 1]
print(subrand)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.