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

后端 未结 3 694
栀梦
栀梦 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:13

    Both of the existing answers are fine; this answer is probably only of interest if you are already using scipy.

    The matrix that you describe is known as a circulant matrix. If you don't mind the dependency on scipy, you can use scipy.linalg.circulant to create one:

    In [136]: from scipy.linalg import circulant
    
    In [137]: ar = np.array([1, 2, 3, 4])
    
    In [138]: circulant(ar[::-1])
    Out[138]: 
    array([[4, 1, 2, 3],
           [3, 4, 1, 2],
           [2, 3, 4, 1],
           [1, 2, 3, 4]])
    

提交回复
热议问题