how to convert a 1d numpy array to a lower triangular matrix?

Question:

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?

Asked By: MoRe

||

Answers:

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]])
Answered By: Valdi_Bo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.