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

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:

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

Thus, each row corresponds ar, which is shifted by row index + 1.

A simple implementation might look like this:

ar_roll = np.tile(ar, ar.shape[0]).reshape(ar.shape[0], ar.shape[0])

for indi, ri in enumerate(ar_roll):
    ar_roll[indi, :] = np.roll(ri, indi + 1)

which gives me the desired result.

My question is is there a smarter way to do this in order to avoid a loop.

+6
source share
3 answers

Here, one approach using NumPy stridesmostly complements the remaining elements, and then strideshelps us in creating this offset version quite efficiently -

def strided_method(ar):
    a = np.concatenate(( ar, ar[:-1] ))
    L = len(ar)
    n = a.strides[0]
    return np.lib.stride_tricks.as_strided(a[L-1:], (L,L), (-n,n))

-

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

In [43]: strided_method(ar)
Out[43]: 
array([[4, 1, 2, 3],
       [3, 4, 1, 2],
       [2, 3, 4, 1],
       [1, 2, 3, 4]])

In [44]: ar = np.array([4,9,3,6,1,2])

In [45]: strided_method(ar)
Out[45]: 
array([[2, 4, 9, 3, 6, 1],
       [1, 2, 4, 9, 3, 6],
       [6, 1, 2, 4, 9, 3],
       [3, 6, 1, 2, 4, 9],
       [9, 3, 6, 1, 2, 4],
       [4, 9, 3, 6, 1, 2]])

-

In [5]: a = np.random.randint(0,9,(1000))

# @Eric soln
In [6]: %timeit roll_matrix(a)
100 loops, best of 3: 3.39 ms per loop

# @Warren Weckesser soln
In [8]: %timeit circulant(a[::-1])
100 loops, best of 3: 2.03 ms per loop

# Strides method
In [18]: %timeit strided_method(a)
100000 loops, best of 3: 6.7 µs per loop

( , ) strides -

In [19]: %timeit strided_method(a).copy()
1000 loops, best of 3: 381 µs per loop
+5

def roll_matrix(vec):
    N = len(vec)
    buffer = np.zeros((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]

buffer

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.]])

, , , 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.]])

, ,

+3

; , , scipy.

, , . scipy, scipy.linalg.circulant, :

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]])
+3

Source: https://habr.com/ru/post/1016928/


All Articles