Home > database >  Convert 1-D array to upper triangular square matrix (anti-diagonal) in numpy
Convert 1-D array to upper triangular square matrix (anti-diagonal) in numpy

Time:12-17

I have an array as below:

arr = np.numpy([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21])

What I would like to do is to convert this array to an upper triangular square matrix anti-diagonally. The expected output is like below:

output = [
    [1,  2,  3,  4,  5,  6],
    [7,  8,  9,  10, 11, 0],
    [12, 13, 14, 15, 0,  0],
    [16, 17, 18, 0,  0,  0],
    [19, 20, 0,  0,  0,  0],
    [21, 0,  0,  0,  0,  0]
]

the approach that I followed is to create a square matrix that has all zeros and update the indexes using triu_indices.

tri = np.zeros((6, 6))
tri[np.triu_indices(6, 1)] = arr

However, this gives me the error: ValueError: shape mismatch: value array of shape (21,) could not be broadcast to indexing result of shape (15,)

Please note that the sizes of the 1-d and matrix will be always 21 and 6x6 respectively.

Not sure where I make the mistake. Is it right way to go? Or is there a better approach instead of this? I would appreciate for any help.

CodePudding user response:

You need to use k=0 and to modify the column indices (by subtracting the row indices):

arr = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21])

tri = np.zeros((6, 6))
idx, col = np.triu_indices(6, k=0)
tri[idx, col-idx] = arr

Output:

array([[ 1.,  2.,  3.,  4.,  5.,  6.],
       [ 7.,  8.,  9., 10., 11.,  0.],
       [12., 13., 14., 15.,  0.,  0.],
       [16., 17., 18.,  0.,  0.,  0.],
       [19., 20.,  0.,  0.,  0.,  0.],
       [21.,  0.,  0.,  0.,  0.,  0.]])

CodePudding user response:

The two arrays are not compatible by size. You must reshape "arr" to the size of (6,6)

arr = arr.reshape((6, 6))

tri = np.triu(arr)

print(tri)
  • Related