Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate matrix using NumPy (Python)

Tags:

python

numpy

just a quick question, if I have a matrix has n rows and m columns, how can I cut off the 4 sides of the matrix and return a new matrix? (the new matrix would have n-2 rows m-2 columns).

Thanks in advance

like image 523
NONEenglisher Avatar asked Dec 13 '08 16:12

NONEenglisher


People also ask

How do I reduce decimal places in NumPy?

round_() in Python. The numpy. round_() is a mathematical function that rounds an array to the given number of decimals.

How do you round off a matrix in python?

With the help of Numpy matrix. round() method, we are able to round off the values of the given matrix.

How do you delete a matrix in python?

Using the NumPy function np. delete() , you can delete any row and column from the NumPy array ndarray . Specify the axis (dimension) and position (row number, column number, etc.). It is also possible to select multiple rows and columns using a slice or a list.

Which function from NumPy use to return the truncated value of the input element wise?

trunc. Return the truncated value of the input, element-wise.


2 Answers

a[1:-1, 1:-1]
like image 97
Mr Fooz Avatar answered Oct 19 '22 02:10

Mr Fooz


A more general answer is:

a[[slice(1, -1) for _ in a.shape]]
like image 30
jfs Avatar answered Oct 19 '22 02:10

jfs