Wrap / unwrap a vector along the diagonals of an array

I was looking for a way (more efficient, just to write loops to traverse the matrix) to create matrices from the elements specified in a wrapped diagonal order, and to extract the values ​​in that order. As an example, given a = [2,3,4,5,6,7], I would like to be able to generate an array

[  0,  2,  5,  7,
   0,  0,  3,  6,
   0,  0,  0,  4,
   0,  0,  0,  0]

and also be able to repeatedly extract afrom this array.

scipy.sparse.diagsachieves something similar, but as the name suggests, it is intended for sparse arrays. Is there any functionality in numpy that provides this, or some form of diagonal indexing? Or maybe some kind of array conversion that will make this more doable?

+5
source share
3

, , , , , np.triu_indices :

def my_triu_indices(n, k=0):
    rows, cols = np.triu_indices(n, k)
    rows = cols - rows - k
    return rows, cols

:

>>> a = np.array([2,3,4,5,6,7])
>>> b = np.zeros((4, 4), dtype=a.dtype)
>>> b[my_triu_indices(4, 1)] = a
>>> b
array([[0, 2, 5, 7],
       [0, 0, 3, 6],
       [0, 0, 0, 4],
       [0, 0, 0, 0]])
>>> b[my_triu_indices(4, 1)]
array([2, 3, 4, 5, 6, 7])
+5

a , - :

import numpy as np
a = [2,5,7,3,6,4]
b = np.zeros((4,4))
b[np.triu_indices(4,1)] = a
In [11]: b
Out[11]:
array([[ 0.,  2.,  5.,  7.],
       [ 0.,  0.,  3.,  6.],
       [ 0.,  0.,  0.,  4.],
       [ 0.,  0.,  0.,  0.]])

:

In [23]: b[np.triu_indices(4,1)]
Out[23]: array([ 2.,  5.,  7.,  3.,  6.,  4.])
+3

It is not easy, but should work. If we break down how numpy finds diagonal indexes, we can rebuild it to get what you want.

def get_diag_indices(s,k):
    n = s
    if (k >= 0):
        i = np.arange(0,n-k)
        fi = i+k+i*n
    else:
        i = np.arange(0,n+k)
        fi = i+(i-k)*n
    return fi

indices=np.hstack(([get_diag_indices(4,1+x) for x in range(3)]))
a=np.array([2, 3, 4, 5, 6, 7])
out=np.zeros((4,4))

>>> out.flat[indices]=a
>>> out
array([[ 0.,  2.,  5.,  7.],
       [ 0.,  0.,  3.,  6.],
       [ 0.,  0.,  0.,  4.],
       [ 0.,  0.,  0.,  0.]])

>>> out.flat[indices]
array([ 2.,  3.,  4.,  5.,  6.,  7.])
+2
source

All Articles