Search code examples
pythonnumpymathmatrix

Numpy: create upper triangular matrix by repeating sequence adding pad


What is the most efficient way of creating an upper triangular matrix from a given sequence as follows:

Input:

[1, 2, 3, 4, 5]

Output:

[[1, 2, 3, 4, 5],
 [0, 1, 2, 3, 4],
 [0, 0, 1, 2, 3],
 [0, 0, 0, 1, 2],
 [0, 0, 0, 0, 1]

for any sequence


Solution

  • np.triu is what you are looking for: it take an array as parameter and returns an upper triangular matrix (documentation):

    import numpy as np
    
    seq = [1, 2, 3, 4, 5]
    
    res = np.triu(seq)
    

    Output:

    [[1 2 3 4 5]
     [0 2 3 4 5]
     [0 0 3 4 5]
     [0 0 0 4 5]
     [0 0 0 0 5]]