Removing any other item in NumPy

I cannot understand this for life.

I am trying to remove any other element in the second axis of the array. I did it in MATLAB with arr(:,:,2:2:end) = []; but when I tried to do the same in Python and compared the two outputs, I get a different matrix.

I tried arr = np.delete(arr,np.arange(0,arr.shape[2],2),2) and arr = arr[:,:,1::2] , but none of them came up with something that i get with matlab.



Example:



MATLAB

  disp(['before: ',str(arr[21,32,11])]) arr(:,:,2:2:end) = []; disp(['after: ',str(arr[21,32,11])]) 

exit:

  before: 99089 after: 65699 


Python

  print 'before: ' + str(arr[20,31,10]) arr = arr[:,:,1::2] # same output as np.delete(arr,np.arange(0,arr.shape[2],2),2) print 'after: ' + str(arr[20,31,10]) 

exit:

  before: 99089 after: 62360 

I hope I don’t miss something fundamental.

+7
python numpy matlab
source share
1 answer

You are trying to delete every other element, starting from the second element, on the last axis. In other words, you are trying to save all other elements, starting from the first element forward along this axis.

Thus, working along the path of selecting elements instead of deleting elements, the code MATLAB arr(:,:,2:2:end) = [] will be equivalent (neglecting performance numbers):

 arr = arr(:,:,1:2:end) 

In Python / NumPy, this will be:

 arr = arr[:,:,0::2] 

Or simply:

 arr = arr[:,:,::2] 
+4
source share

All Articles