Home > database >  how to convert an 1d numpy array to a lower triangular matrix?
how to convert an 1d numpy array to a lower triangular matrix?

Time:06-10

I have a numpy array like:

np.array([1,2,3,4])

and I want to convert it to a lower triangular matrix like

np.array([
    [4, 0, 0, 0],
    [3, 4, 0, 0],
    [2, 3, 4, 0],
    [1, 2, 3, 4]
])

, without for loop.... how can i do it?

CodePudding user response:

A similar solution to proposed in a comment by Michael Szczesny can be:

b = np.arange(a.size)
result = np.tril(np.take(a, b - b[:,None]   a.size - 1, mode='clip'))

The result is:

array([[4, 0, 0, 0],
       [3, 4, 0, 0],
       [2, 3, 4, 0],
       [1, 2, 3, 4]])
  • Related