numpy fill_diagonal返回None [英] Numpy fill_diagonal return None

查看:64
本文介绍了numpy fill_diagonal返回None的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成对称的零对角矩阵.我的对称零件可以工作,但是当我使用numpy中的fill_diagonal作为结果时,结果为无".我的代码如下.感谢您阅读

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)

与python/numpy中的许多其他方法一样,

推荐答案

np.fill_diagonal()可以就地工作.例如:为什么"return list.sort() "返回None,而不是列表?.那是因为它直接更改了内存中的对象,而不创建新对象.这些函数的返回值为None.因此,请更改:

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)

只是:

np.fill_diagonal(symmetric_matrix,0)

然后您将看到反映在symmetric_matrix中的更改.

You will then see the change reflected in symmetric_matrix.

这篇关于numpy fill_diagonal返回None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆