Dr Simhachalam
Dr Simhachalam

Reputation: 11

How to create an upper triangular matrix where elements in each row increase in a sequence?

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

Answers (1)

pho
pho

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

Try it online

Upvotes: 1

Related Questions