Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D array Of All Cyclic Shifts Of A 1D array

Suppose a is some 1d numppy.array with n elements:

a = np.array([a_0, a_1, ..., a_n_minus_1])

I'd like to generate the 2d (n X n) numpy.array containing, at row i, the ith cyclic shift of a:

np.array([[a_0, a_1, ..., a_n_minus_1], [a_n_minus_1, a_0, a_1, ...], ...]])

preferably without loops. How can this be done efficiently?

(The function np.roll seems related, but apparently takes only a scalar shift.)

like image 780
Ami Tavory Avatar asked Mar 10 '16 18:03

Ami Tavory


1 Answers

you are actually building a circulant matrix. Just use the scipy circulant function. Be careful, because you must pass in the first vertical column, not first row:

from scipy.linalg import circulant
circulant([1,4,3,2]
> array([[1, 2, 3, 4],
         [4, 1, 2, 3],
         [3, 4, 1, 2],
         [2, 3, 4, 1]]

For reference, circulant matrices have very very nice properties.

like image 74
gg349 Avatar answered Nov 02 '22 20:11

gg349