0

I am trying to modify the diagonal values of a 6 x 5 2D numpy array (It's an exercise in this scipy tutorial: http://scipy-lectures.org/intro/numpy/array_object.html#basic-visualization). I'm supposed to change the values of a diagonal from zeroes to 2,3,4,5,6. Since it's a 6 x 5 matrix, there's not really a "main" diagonal, and so I need to change the diagonal starting from the second row ([1][0]) to [5][4]. They suggest reading the docstring for diag. I did, and I still can't figure out how to do this. Any suggestions?

1
  • arr[[1,2,3,4,5], [0,1,2,3,4]] indexes that diagonal. Make np.arange(30).reshape(6,5) and test it. Commented Jul 1, 2019 at 2:48

1 Answer 1

2

You can just slice an array, and fill_diagonal of that:

In [13]: import numpy as np                                                     

In [14]: a = np.zeros((6,5), int)                                               

In [15]: np.fill_diagonal(a[1:], [2,3,4,5,6])                                   

In [16]: a                                                                      
Out[16]: 
array([[0, 0, 0, 0, 0],
       [2, 0, 0, 0, 0],
       [0, 3, 0, 0, 0],
       [0, 0, 4, 0, 0],
       [0, 0, 0, 5, 0],
       [0, 0, 0, 0, 6]])
Sign up to request clarification or add additional context in comments.

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.