How do I remove the first and last rows and columns from a 2D numpy array?

 I'd like to know how to remove the first and last rows and columns from a 2D array in numpy. For example, say we have a (N+1) x (N+1) matrix called H then in MATLAB/Octave, the code I'd use would be: 

 

Hsub = H(2:N,2:N);

What's the equivalent code in Numpy? I thought that np.reshape might do what I want but I'm not sure how to get it to remove just the target rows as I think if I reshape to a (N-1) x (N-1) matrix, it'll remove the last two rows and columns.  

NOTE:-


Matlabsolutions.com provide latest MatLab Homework Help,MatLab Assignment Help , Finance Assignment Help for students, engineers and researchers in Multiple Branches like ECE, EEE, CSE, Mechanical, Civil with 100% output.Matlab Code for B.E, B.Tech,M.E,M.Tech, Ph.D. Scholars with 100% privacy guaranteed. Get MATLAB projects with source code for your learning and research.  
 

Answer: 

How about this? 

 

Hsub = H[1:-1, 1:-1]

The 1:-1 range means that we access elements from the second index, or 1, and we go up to the second last index, as indicated by the -1 for a dimension. We do this for both dimensions independently. When you do this independently for both dimensions, the result is the intersection of how you're accessing each dimension, which is essentially chopping off the first row, first column, last row and last column. 

Remember, the ending index is exclusive, so if we did 0:3 for example, we only get the first three elements of a dimension, not four. 

Also, negative indices mean that we access the array from the end-1 is the last value to access in a particular dimension, but because of the exclusivity, we are getting up to the second last element, not the last element. Essentially, this is the same as doing: 

 

Hsub = H[1:H.shape[0]-1, 1:H.shape[1]-1]

... but using negative indices is much more elegant. You also don't have to use the number of rows and columns to extract out what you need. The above syntax is dimension agnostic. However, you need to make sure that the matrix is at least 3 x 3, or you'll get an error. 

How about this?

Hsub = H[1:-1, 1:-1]

The 1:-1 range means that we access elements from the second index, or 1, and we go up to the second last index, as indicated by the -1 for a dimension. We do this for both dimensions independently. When you do this independently for both dimensions, the result is the intersection of how you're accessing each dimension, which is essentially chopping off the first row, first column, last row and last column. 


SEE COMPLETE ANSWER CLICK THE LINK  

https://matlabhelpers.com/questions/how-do-i-remove-the-first-and-last-rows-and-columns-from-a-2d-numpy-array-.php

Comments

Popular posts from this blog

Why do I get a "Too many input arguments" error when not passing any?

Why Red, Green, Blue channels of image separetely are grayscaled (Matlab)?

How is full convolution performed using MATLAB's conv2 function?