python - 如何更改numpy中矩阵对角线的值?

标签 python numpy

<分区>

我想将一些 numpy 矩阵的对角线设置为任意一维数组。

例如,如果:

mat = np.array([[1,2],[3,4]])
diag = np.array([5,6])

然后:

>>> set_diagonal(mat, diag)
>>> mat
... array([[5,2],
           [3,6]])

可以diag 变量创建对角矩阵,diag_fill mat 矩阵到 0 并添加结果。但是,如果我试图就地改变对角线,这似乎会使用一堆不必要的资源。

如何在 numpy 中设置矩阵的对角线?

注意:这不是 this question 的副本,因为他们想将对角线设置为常量

最佳答案

您正在寻找numpy.fill_diagonal

根据文档:

numpy.fill_diagonal(a, val, wrap=False) .
Fill the main diagonal of the given array of any dimensionality.

import numpy as np
mat = np.array([[1,2],[3,4]])

np.fill_diagonal(mat, [5,6])
print(mat)
#[[5 2]
# [3 6]]

或者

import numpy as np
mat = np.array([[1,2],[3,4]])
diag = np.array([5,6])
np.fill_diagonal(mat, diag)
print(mat)
#[[5 2]
# [3 6]]

关于python - 如何更改numpy中矩阵对角线的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55940915/

相关文章:

python - 谷歌应用引擎 : how can I programmatically access the properties of my Model class?

python - 为什么我的正则表达式与我需要的电话号码不匹配?

python - 用 pandas 计算列的 "energy"

python - 建议为达到最大连接限制而引发的异常类型

Python:如何删除以多行关键字开头的字符串的一部分?

python - 使用 numpy 数组计算相似元组的数量

python - 使用 PIL 对图像进行矢量化 reshape 和裁剪

python - savetxt 到文件给出错误

python - 如何使用 pyplot 正确显示图像的红色、绿色和蓝色 (rgb) channel

python - A[0] 和 A[0 :1] numpy arrays in python 之间的区别