Numpy: create upper triangular matrix by repeating sequence adding pad

Viewed 519

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

1 Answers

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]]
Related