Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy fill_diagonal return None

Tags:

python

numpy

I want to generate symmetric zero diagonal matrices. My symmetric part work, but when I use fill_diagonal from numpy as the result I got "None". My code is below. Thank you for reading

import numpy as np
matrix_size = int(input("Size of the matrix \n"))
random_matrix = np.random.random_integers(-4,4,size=(matrix_size,matrix_size))
symmetric_matrix = (random_matrix + random_matrix.T)/2
print(symmetric_matrix)
zero_diogonal_matrix = np.fill_diagonal(symmetric_matrix,0)
print(zero_diogonal_matrix)
like image 921
Dancer PhD Avatar asked Sep 14 '25 11:09

Dancer PhD


2 Answers

np.fill_diagonal(), like many other methods across python/numpy, works in-place. For example: Why does “return list.sort()” return None, not the list?. That is that it directly alters the object in memory and does not create a new object. The return value from such functions is None. Therefore, change:

zero_diogonal_matrix = np.fill_diagonal(symmetric_matrix,0)

To just:

np.fill_diagonal(symmetric_matrix,0)

You will then see the change reflected in symmetric_matrix.

like image 66
roganjosh Avatar answered Sep 17 '25 01:09

roganjosh


It's probably overkill, but in case you want to preserve the tenet of minimising surprise, you could wrap this (and other functions like it) in a function that takes care of preserving the original array:

def fill_diagonal(source_array, diagonal):
    copy = source_array.copy()
    np.fill_diagonal(copy, diagonal)
    return copy

But the question then becomes "who exactly is going to be least surprised by doing it this way?"

like image 22
Thomas Kimber Avatar answered Sep 17 '25 01:09

Thomas Kimber