Reputation: 11
I tried the below code:
arr = np.triu(np.ones((5, 5)))
arr[arr > 1] = np.arange(1, np.sum(arr > 1) + 1)
print(arr)
i expect for ex n=5 that would be
[[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.]]
Upvotes: 1
Views: 50
Reputation: 25489
You can create the triu
of an array of ones, and calculate the cumulative sum along the 1
axis:
import numpy as np
n=5
arr = np.cumsum(
np.triu(
np.ones((n, n))
), axis=1)
print(arr)
Gives:
[[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.]]
Upvotes: 1