0

I have a 5x5 matrix:

>>> import numpy as np
>>> x=np.random.rand(5,5)
>>> x
array([[ 0.47231299,  0.02139265,  0.05321461,  0.06338545,  0.98003833],
       [ 0.81340571,  0.81404643,  0.87641499,  0.29969447,  0.13871426],
       [ 0.91088258,  0.02642179,  0.03657303,  0.91060929,  0.2442742 ],
       [ 0.55178147,  0.54428098,  0.21511229,  0.2177599 ,  0.52179989],
       [ 0.29138135,  0.06855664,  0.63419486,  0.154126  ,  0.1939914 ]])

I want to clip this matrix. Let's say I want the data without first and last row and also without first and last column. How to do this?

This might seem like a basic question. However, I could not understand how indexing works for 2D or multidimensional matrix, so that clipping can be done accordingly.

1 Answer 1

3

Basic numpy indexing/slicing:

x[1:-1,1:-1]

#array([[ 0.81404643,  0.87641499,  0.29969447],
#       [ 0.02642179,  0.03657303,  0.91060929],
#       [ 0.54428098,  0.21511229,  0.2177599 ]])
Sign up to request clarification or add additional context in comments.

2 Comments

Ah I see! I was trying indices in this format x[...][...] and not in this format x[..., ...]. The x[][] acts as a clip only for rows, but clip of clips...
x[...,...,...] syntax is how you would slice ndarrays. Just note that x[1:-1][:,1:-1] works as well but not as idiomatic as the former.

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.