2

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

Federico Taschin
  • 2,027
  • 3
  • 15
  • 28
  • From linked one's accepted answer, for `sliding_windows`, edit `b = np.concatenate((p,a))` and `return strided(b[W-1:], shape=(W,len(a)), strides=(-s,s))`. – Divakar Jun 17 '20 at 16:01
  • Or with existing one `sliding_windows(a,len(a))[:,:len(a)]`. – Divakar Jun 17 '20 at 16:05

1 Answers1

2

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]]
Zephyr
  • 11,891
  • 53
  • 45
  • 80