Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy modify ndarray diagonal

Tags:

python

numpy

is there any way in numpy to get a reference to the array diagonal? I want my array diagonal to be divided by a certain factor Thanks

like image 451
Luca Fiaschi Avatar asked Sep 12 '11 22:09

Luca Fiaschi


People also ask

How do you change the diagonal elements of a matrix in numpy?

With the help of numpy. fill_diagonal() method, we can get filled the diagonals of numpy array with the value passed as the parameter in numpy. fill_diagonal() method. Return : Return the filled value in the diagonal of an array.

Which method can change the shape of Ndarray?

To convert the shape of a NumPy array ndarray , use the reshape() method of ndarray or the numpy.


2 Answers

If X is your array and c is the factor,

X[np.diag_indices_from(X)] /= c

See diag_indices_from in the Numpy manual.

like image 128
Fred Foo Avatar answered Sep 30 '22 17:09

Fred Foo


A quick way to access the diagonal of a square (n,n) numpy array is with arr.flat[::n+1]:

n = 1000
c = 20
a = np.random.rand(n,n)

a[np.diag_indices_from(a)] /= c # 119 microseconds
a.flat[::n+1] /= c # 25.3 microseconds
like image 33
kwgoodman Avatar answered Sep 30 '22 15:09

kwgoodman