Reputation: 1612
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?
Upvotes: 0
Views: 87
Reputation: 86218
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]])
Upvotes: 2