Create a matrix from a vector where each row is a shifted version of the vector

后端 未结 3 690
栀梦
栀梦 2020-12-19 06:49

I have a numpy array like this

import numpy as np

ar = np.array([1, 2, 3, 4])

and I want to create an array that looks like this:

3条回答
  •  盖世英雄少女心
    2020-12-19 07:15

    Here's one approach

    def roll_matrix(vec):
        N = len(vec)
        buffer = np.empty((N, N*2 - 1))
    
        # generate a wider array that we want a slice into
        buffer[:,:N] = vec
        buffer[:,N:] = vec[:-1]
    
        rolled = buffer.reshape(-1)[N-1:-1].reshape(N, -1)
        return rolled[:,:N]
    

    In your case, we build buffer to be

    array([[ 1.,  2.,  3.,  4.,  1.,  2.,  3.],
           [ 1.,  2.,  3.,  4.,  1.,  2.,  3.],
           [ 1.,  2.,  3.,  4.,  1.,  2.,  3.],
           [ 1.,  2.,  3.,  4.,  1.,  2.,  3.]])
    

    Then flatten it, trim it, reshape it to get rolled:

    array([[ 4.,  1.,  2.,  3.,  1.,  2.],
           [ 3.,  4.,  1.,  2.,  3.,  1.],
           [ 2.,  3.,  4.,  1.,  2.,  3.],
           [ 1.,  2.,  3.,  4.,  1.,  2.]])
    

    And finally, slice off the garbage last columns

提交回复
热议问题