0

I would like to create a square numpy array such that it starts counting from the diagonal. Do you know a one-liner for that?

Example with 5x5:

array([[ 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.]])

2 Answers 2

2
In [49]: np.identity(5).cumsum(axis=1).cumsum(axis=1)
Out[49]:
array([[ 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.]]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the solution. Here is what I ended up using for readability: np.triu(np.ones([K,K]), 0).cumsum(axis =1)
That's a cool one too. Ran a quick timing test and both methods end up being almost exactly the same (254ms vs. 257ms per run on a 5000x5000 grid), so either way should be work from a performance point of view.
0
>>> mat = np.vstack((np.concatenate((np.zeros(i),np.arange(1,5-i+1))) for i in range(0,5)))
>>> mat 
array([[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.]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.