python - numpy matrix arithmetic with its diagonal element -


i love numpy because allows vectorized operation such as:

mat1 = np.array([[1,2],[3,4]]) mat2 = np.array([[10,20],[30,40]]) mat3 = (mat1 + mat2)*2.0 # vectorization way. nice. 

but, can not find how kind of operation diagonal elements. i'd

b_{ij}=1/(a_{i,i}+a_{j,j}-2*a_{i,j})

b_{ij}=a_{i,j}/\sqrt{a_{i,i}*a_{j,j}}

is possible operate above in vectorization way numpy?

for first exemple :

with :

in [3]: """  array([[1, 3, 4, 0, 4],        [2, 3, 3, 3, 0],        [1, 0, 4, 1, 0],        [0, 3, 3, 2, 0],        [2, 1, 0, 3, 2]]) """  in [4]: aii=vstack((diag(a),)*a.shape[0]) """ array([[1, 3, 4, 2, 2],        [1, 3, 4, 2, 2],        [1, 3, 4, 2, 2],        [1, 3, 4, 2, 2],        [1, 3, 4, 2, 2]]) """  in [5]: ajj=aii.t # transpose in [6]: b= 1/ (aii+ajj-2*a)     

or, more abstract tools :

b1 = 1 / (np.add.outer(diag(a),diag(a))-2*a) b2 = / np.sqrt(np.multiply.outer(diag(a),diag(a))) 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -