我看到一个函数 numpy.fill_diagonal
为对角线元素分配相同的值。但我想为每个对角线元素分配不同的随机值。我怎样才能在 python 中做到这一点?可能正在使用 scipy 或其他库?
最佳答案
即docs将填充 val
称为标量 is an existing documentation bug .事实上,任何可以在这里广播的值都是可以的。
填充对角线可以很好地处理类数组:
>>> 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]])
这是一个跨步技巧,因为对角线元素按数组的宽度 + 1 规则间隔。
从文档字符串来看,这比使用 np.diag_indices
更好:
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.
关于python - 为每个 python numpy 用不同的值填充矩阵对角线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40261325/