1

I have a question, how can I generate an array of slices from a numpy array. I can do it with for loop, what I am trying to do is:

def calc_matrix(arr, k): 
    x = np.zeros((len(arr) - k + 1, k))
    for i in range(len(arr) - k + 1):
        x[i, :] = arr[i: (i+k)]
    return x
4
  • 2
    For clarity, can you provide examples for arr and k? Commented Apr 26, 2018 at 11:10
  • also, can you clarify what the technical reason is that you want to get rid of the for loop ? Commented Apr 26, 2018 at 11:11
  • Avoiding for loops and using operations which work on many array elements is much faster in numpy for many operations. Commented Apr 26, 2018 at 11:16
  • 1
    @jpp arr = np.arange(20) and k is 4 for example, I meant that arr is 1D array, sorry for not mentioning that. Commented May 4, 2018 at 14:32

1 Answer 1

2

You can cut your desired result out of the Hankel matrix of arr (and an arbitrary second parameter; below we leave it out completely in which case zeros are used per default):

>>> import numpy as np                                                                                              
>>> from scipy import linalg
>>>
>>> arr = np.arange(10)**2 % 7   ##  just a random example      
>>> arr
array([0, 1, 4, 2, 2, 4, 1, 0, 1, 4])                                            
>>> k = 4                                                                                                           
>>> linalg.hankel(arr)[:arr.size-k+1, :k]                                              
array([[0, 1, 4, 2],                                                                                                
       [1, 4, 2, 2],                                                                                                
       [4, 2, 2, 4],                                                                                                
       [2, 2, 4, 1],                                                                                                
       [2, 4, 1, 0],
       [4, 1, 0, 1],
       [1, 0, 1, 4]])

Or you could use http://scikit-image.org/docs/dev/api/skimage.util.html#skimage.util.view_as_windows.

Sign up to request clarification or add additional context in comments.

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.