Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill matrix diagonal with different values for each python numpy

Tags:

python

numpy

I saw a function numpy.fill_diagonal which assigns same value for diagonal elements. But I want to assign different random values for each diagonal elements. How can I do it in python ? May be using scipy or other libraries ?

like image 461
Shyamkkhadka Avatar asked Oct 26 '16 11:10

Shyamkkhadka


Video Answer


1 Answers

That the docs call the fill val a scalar is an existing documentation bug. In fact, any value that can be broadcasted here is OK.

Fill diagonal works fine with array-likes:

>>> a = np.arange(1,10).reshape(3,3)
>>> a
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> np.fill_diagonal(a, [99, 42, 69])
>>> a
array([[99,  2,  3],
       [ 4, 42,  6],
       [ 7,  8, 69]])

It's a stride trick, since the diagonal elements are regularly spaced by the array's width + 1.

From the docstring, that's a better implementation than using np.diag_indices too:

Notes
-----
.. versionadded:: 1.4.0

This functionality can be obtained via `diag_indices`, but internally
this version uses a much faster implementation that never constructs the
indices and uses simple slicing.
like image 172
wim Avatar answered Oct 04 '22 13:10

wim