How to create a specific upper triangular matrix?

Viewed 73

I would like to create in python (using numpy) an upper triangular matrix in the form:

[[ 1,  c,  c^2],
 [ 0,  1,  c  ],
 [ 0,  0,  1  ]])

where c is a rational number and the rank of the matrix may vary (2, 3, 4, ...). Is there any smart way to do it other than creating rows and stacking them?

2 Answers

There are probably more straightforward solutions but this is what I came up with:

import numpy as np

c=5
m=np.triu(c**np.triu(np.ones((3,3)), 1).cumsum(axis =1))
print(m)

output:

[[ 1.  5. 25.]
 [ 0.  1.  5.]
 [ 0.  0.  1.]]
r = 3
c = 3
i,j = np.indices((r,r))
np.triu(float(c)**(j-i))

Result:

array([[1., 3., 9.],
       [0., 1., 3.],
       [0., 0., 1.]])
Related